blob: f616a10524ed02eee5b120d2be436d7584fc25f9 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000031#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000032#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000033#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000034#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000035#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000038
Chris Lattner60800082009-02-18 17:49:48 +000039SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000041 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000043}
Chris Lattner08f92e32010-11-17 07:37:15 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045
Ryan Flynn4403a5e2009-08-06 03:00:50 +000046/// CheckablePrintfAttr - does a function call have a "printf" attribute
47/// and arguments that merit checking?
48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49 if (Format->getType() == "printf") return true;
50 if (Format->getType() == "printf0") {
51 // printf0 allows null "format" string; if so don't check format/args
52 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000053 // Does the index refer to the implicit object argument?
54 if (isa<CXXMemberCallExpr>(TheCall)) {
55 if (format_idx == 0)
56 return false;
57 --format_idx;
58 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000059 if (format_idx < TheCall->getNumArgs()) {
60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000061 if (!Format->isNullPointerConstant(Context,
62 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000063 return true;
64 }
65 }
66 return false;
67}
Chris Lattner60800082009-02-18 17:49:48 +000068
John McCall8e10f3b2011-02-26 05:39:39 +000069/// Checks that a call expression's argument count is the desired number.
70/// This is useful when doing custom type-checking. Returns true on error.
71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
72 unsigned argCount = call->getNumArgs();
73 if (argCount == desiredArgCount) return false;
74
75 if (argCount < desiredArgCount)
76 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
77 << 0 /*function call*/ << desiredArgCount << argCount
78 << call->getSourceRange();
79
80 // Highlight all the excess arguments.
81 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
82 call->getArg(argCount - 1)->getLocEnd());
83
84 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
85 << 0 /*function call*/ << desiredArgCount << argCount
86 << call->getArg(1)->getSourceRange();
87}
88
John McCall60d7b3a2010-08-24 06:29:42 +000089ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000090Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000091 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000092
Chris Lattner946928f2010-10-01 23:23:24 +000093 // Find out if any arguments are required to be integer constant expressions.
94 unsigned ICEArguments = 0;
95 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
Anders Carlssond406bf02009-08-16 01:56:34 +0000111 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000113 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000114 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000115 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000116 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000117 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000118 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000119 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000120 if (SemaBuiltinVAStart(TheCall))
121 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000122 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 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:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinUnorderedCompare(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000132 case Builtin::BI__builtin_fpclassify:
133 if (SemaBuiltinFPClassification(TheCall, 6))
134 return ExprError();
135 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000136 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:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000141 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000142 return ExprError();
143 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000144 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 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.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000148 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000149 if (SemaBuiltinPrefetch(TheCall))
150 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000151 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000152 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 if (SemaBuiltinObjectSize(TheCall))
154 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000155 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000156 case Builtin::BI__builtin_longjmp:
157 if (SemaBuiltinLongjmp(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000160
161 case Builtin::BI__builtin_classify_type:
162 if (checkArgCount(*this, TheCall, 1)) return true;
163 TheCall->setType(Context.IntTy);
164 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000165 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000166 if (checkArgCount(*this, TheCall, 1)) return true;
167 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000168 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000169 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:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000183 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000184 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000185 }
186
187 // Since the target specific builtins for each arch overlap, only check those
188 // of the arch we are compiling for.
189 if (BuiltinID >= Builtin::FirstTSBuiltin) {
190 switch (Context.Target.getTriple().getArch()) {
191 case llvm::Triple::arm:
192 case llvm::Triple::thumb:
193 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
194 return ExprError();
195 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000196 default:
197 break;
198 }
199 }
200
201 return move(TheCallResult);
202}
203
Nate Begeman61eecf52010-06-14 05:21:25 +0000204// Get the valid immediate range for the specified NEON type code.
205static unsigned RFT(unsigned t, bool shift = false) {
206 bool quad = t & 0x10;
207
208 switch (t & 0x7) {
209 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000210 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000211 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000212 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000213 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000214 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000216 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 case 4: // f32
218 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000219 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000220 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000221 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000222 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000223 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000224 case 7: // float16
225 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000226 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000227 }
228 return 0;
229}
230
Nate Begeman26a31422010-06-08 02:47:44 +0000231bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000232 llvm::APSInt Result;
233
Nate Begeman0d15c532010-06-13 04:47:52 +0000234 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000235 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000236 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000237#define GET_NEON_OVERLOAD_CHECK
238#include "clang/Basic/arm_neon.inc"
239#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000240 }
241
Nate Begeman0d15c532010-06-13 04:47:52 +0000242 // For NEON intrinsics which are overloaded on vector element type, validate
243 // the immediate which specifies which variant to emit.
244 if (mask) {
245 unsigned ArgNo = TheCall->getNumArgs()-1;
246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 return true;
248
Nate Begeman61eecf52010-06-14 05:21:25 +0000249 TV = Result.getLimitedValue(32);
250 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000251 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
252 << TheCall->getArg(ArgNo)->getSourceRange();
253 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000254
Nate Begeman0d15c532010-06-13 04:47:52 +0000255 // For NEON intrinsics which take an immediate value as part of the
256 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000258 switch (BuiltinID) {
259 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000260 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
261 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000262 case ARM::BI__builtin_arm_vcvtr_f:
263 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000264#define GET_NEON_IMMEDIATE_CHECK
265#include "clang/Basic/arm_neon.inc"
266#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000267 };
268
Nate Begeman61eecf52010-06-14 05:21:25 +0000269 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000270 if (SemaBuiltinConstantArg(TheCall, i, Result))
271 return true;
272
Nate Begeman61eecf52010-06-14 05:21:25 +0000273 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000274 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000277 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000278
Nate Begeman99c40bb2010-08-03 21:32:34 +0000279 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000280 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000281}
Daniel Dunbarde454282008-10-02 18:44:07 +0000282
Anders Carlssond406bf02009-08-16 01:56:34 +0000283/// CheckFunctionCall - Check a direct function call for various correctness
284/// and safety properties not strictly enforced by the C type system.
285bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
286 // Get the IdentifierInfo* for the called function.
287 IdentifierInfo *FnInfo = FDecl->getIdentifier();
288
289 // None of the checks below are needed for functions that don't have
290 // simple names (e.g., C++ conversion functions).
291 if (!FnInfo)
292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Daniel Dunbarde454282008-10-02 18:44:07 +0000294 // FIXME: This mechanism should be abstracted to be less fragile and
295 // more efficient. For example, just map function ids to custom
296 // handlers.
297
Ted Kremenekc82faca2010-09-09 04:33:05 +0000298 // Printf and scanf checking.
299 for (specific_attr_iterator<FormatAttr>
300 i = FDecl->specific_attr_begin<FormatAttr>(),
301 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
302
303 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000304 const bool b = Format->getType() == "scanf";
305 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000306 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000307 CheckPrintfScanfArguments(TheCall, HasVAListArg,
308 Format->getFormatIdx() - 1,
309 HasVAListArg ? 0 : Format->getFirstArg() - 1,
310 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000311 }
Chris Lattner59907c42007-08-10 20:18:51 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Ted Kremenekc82faca2010-09-09 04:33:05 +0000314 for (specific_attr_iterator<NonNullAttr>
315 i = FDecl->specific_attr_begin<NonNullAttr>(),
316 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000317 CheckNonNullArguments(*i, TheCall->getArgs(),
318 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000319 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000320
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000321 // Memset handling
322 if (FnInfo->isStr("memset"))
323 CheckMemsetArguments(TheCall);
324
Anders Carlssond406bf02009-08-16 01:56:34 +0000325 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000326}
327
Anders Carlssond406bf02009-08-16 01:56:34 +0000328bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000329 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000330 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000331 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000332 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000334 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
335 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000336 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000338 QualType Ty = V->getType();
339 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Ted Kremenek826a3452010-07-16 02:11:22 +0000342 const bool b = Format->getType() == "scanf";
343 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000344 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlssond406bf02009-08-16 01:56:34 +0000346 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000347 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
348 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000349
350 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000351}
352
Chris Lattner5caa3702009-05-08 06:58:22 +0000353/// SemaBuiltinAtomicOverloaded - We have a call to a function like
354/// __sync_fetch_and_add, which is an overloaded function based on the pointer
355/// type of its first argument. The main ActOnCallExpr routines have already
356/// promoted the types of arguments because all of these calls are prototyped as
357/// void(...).
358///
359/// This function goes through and does final semantic checking for these
360/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000361ExprResult
362Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000363 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000364 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
365 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
366
367 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000368 if (TheCall->getNumArgs() < 1) {
369 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
370 << 0 << 1 << TheCall->getNumArgs()
371 << TheCall->getCallee()->getSourceRange();
372 return ExprError();
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 // Inspect the first argument of the atomic builtin. This should always be
376 // a pointer type, whose element is an integral scalar or pointer type.
377 // Because it is a pointer type, we don't have to worry about any implicit
378 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000379 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000380 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000381 if (!FirstArg->getType()->isPointerType()) {
382 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
383 << FirstArg->getType() << FirstArg->getSourceRange();
384 return ExprError();
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chandler Carruthd2014572010-07-09 18:59:35 +0000387 QualType ValType =
388 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000390 !ValType->isBlockPointerType()) {
391 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
392 << FirstArg->getType() << FirstArg->getSourceRange();
393 return ExprError();
394 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000395
Chandler Carruth8d13d222010-07-18 20:54:12 +0000396 // The majority of builtins return a value, but a few have special return
397 // types, so allow them to override appropriately below.
398 QualType ResultType = ValType;
399
Chris Lattner5caa3702009-05-08 06:58:22 +0000400 // We need to figure out which concrete builtin this maps onto. For example,
401 // __sync_fetch_and_add with a 2 byte object turns into
402 // __sync_fetch_and_add_2.
403#define BUILTIN_ROW(x) \
404 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
405 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 static const unsigned BuiltinIndices[][5] = {
408 BUILTIN_ROW(__sync_fetch_and_add),
409 BUILTIN_ROW(__sync_fetch_and_sub),
410 BUILTIN_ROW(__sync_fetch_and_or),
411 BUILTIN_ROW(__sync_fetch_and_and),
412 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 BUILTIN_ROW(__sync_add_and_fetch),
415 BUILTIN_ROW(__sync_sub_and_fetch),
416 BUILTIN_ROW(__sync_and_and_fetch),
417 BUILTIN_ROW(__sync_or_and_fetch),
418 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner5caa3702009-05-08 06:58:22 +0000420 BUILTIN_ROW(__sync_val_compare_and_swap),
421 BUILTIN_ROW(__sync_bool_compare_and_swap),
422 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000423 BUILTIN_ROW(__sync_lock_release),
424 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 };
Mike Stump1eb44332009-09-09 15:08:12 +0000426#undef BUILTIN_ROW
427
Chris Lattner5caa3702009-05-08 06:58:22 +0000428 // Determine the index of the size.
429 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000430 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000431 case 1: SizeIndex = 0; break;
432 case 2: SizeIndex = 1; break;
433 case 4: SizeIndex = 2; break;
434 case 8: SizeIndex = 3; break;
435 case 16: SizeIndex = 4; break;
436 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000437 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
438 << FirstArg->getType() << FirstArg->getSourceRange();
439 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner5caa3702009-05-08 06:58:22 +0000442 // Each of these builtins has one pointer argument, followed by some number of
443 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
444 // that we ignore. Find out which row of BuiltinIndices to read from as well
445 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000446 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000447 unsigned BuiltinIndex, NumFixed = 1;
448 switch (BuiltinID) {
449 default: assert(0 && "Unknown overloaded atomic builtin!");
450 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
451 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
452 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
453 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
454 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000456 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
457 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
458 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
459 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
460 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner5caa3702009-05-08 06:58:22 +0000462 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000463 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000464 NumFixed = 2;
465 break;
466 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000467 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000469 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000471 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000472 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000473 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000475 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000477 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner5caa3702009-05-08 06:58:22 +0000480 // Now that we know how many fixed arguments we expect, first check that we
481 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000482 if (TheCall->getNumArgs() < 1+NumFixed) {
483 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
484 << 0 << 1+NumFixed << TheCall->getNumArgs()
485 << TheCall->getCallee()->getSourceRange();
486 return ExprError();
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000489 // Get the decl for the concrete builtin from this, we can tell what the
490 // concrete integer type we should convert to is.
491 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
492 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
493 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000494 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000495 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
496 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000497
John McCallf871d0c2010-08-07 06:22:56 +0000498 // The first argument --- the pointer --- has a fixed type; we
499 // deduce the types of the rest of the arguments accordingly. Walk
500 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000502 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner5caa3702009-05-08 06:58:22 +0000504 // If the argument is an implicit cast, then there was a promotion due to
505 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000506 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000507 Arg = ICE->getSubExpr();
508 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000509 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner5caa3702009-05-08 06:58:22 +0000512 // GCC does an implicit conversion to the pointer or integer ValType. This
513 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000514 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000515 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000516 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000517 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath);
518 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000519 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Chris Lattner5caa3702009-05-08 06:58:22 +0000521 // Okay, we have something that *can* be converted to the right type. Check
522 // to see if there is a potentially weird extension going on here. This can
523 // happen when you do an atomic operation on something like an char* and
524 // pass in 42. The 42 gets converted to char. This is even more strange
525 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000526 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000527 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
528 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner5caa3702009-05-08 06:58:22 +0000531 // Switch the DeclRefExpr to refer to the new decl.
532 DRE->setDecl(NewBuiltinDecl);
533 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Chris Lattner5caa3702009-05-08 06:58:22 +0000535 // Set the callee in the CallExpr.
536 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000537 ExprResult PromotedCall = UsualUnaryConversions(DRE);
538 if (PromotedCall.isInvalid())
539 return ExprError();
540 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000542 // Change the result type of the call to match the original value type. This
543 // is arbitrary, but the codegen for these builtins ins design to handle it
544 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000545 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000546
547 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000548}
549
550
Chris Lattner69039812009-02-18 06:01:06 +0000551/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000552/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000553/// Note: It might also make sense to do the UTF-16 conversion here (would
554/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000555bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000556 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000557 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
558
559 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000560 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
561 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000562 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000563 }
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000565 if (Literal->containsNonAsciiOrNull()) {
566 llvm::StringRef String = Literal->getString();
567 unsigned NumBytes = String.size();
568 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
569 const UTF8 *FromPtr = (UTF8 *)String.data();
570 UTF16 *ToPtr = &ToBuf[0];
571
572 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
573 &ToPtr, ToPtr + NumBytes,
574 strictConversion);
575 // Check for conversion failure.
576 if (Result != conversionOK)
577 Diag(Arg->getLocStart(),
578 diag::warn_cfstring_truncated) << Arg->getSourceRange();
579 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000580 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000581}
582
Chris Lattnerc27c6652007-12-20 00:05:45 +0000583/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
584/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000585bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
586 Expr *Fn = TheCall->getCallee();
587 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000588 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000590 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
591 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000592 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000593 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000594 return true;
595 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000596
597 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000598 return Diag(TheCall->getLocEnd(),
599 diag::err_typecheck_call_too_few_args_at_least)
600 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000601 }
602
Chris Lattnerc27c6652007-12-20 00:05:45 +0000603 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000604 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000605 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000606 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000607 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000608 else if (FunctionDecl *FD = getCurFunctionDecl())
609 isVariadic = FD->isVariadic();
610 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000611 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Chris Lattnerc27c6652007-12-20 00:05:45 +0000613 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000614 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
615 return true;
616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner30ce3442007-12-19 23:59:04 +0000618 // Verify that the second argument to the builtin is the last argument of the
619 // current function or method.
620 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000621 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlsson88cf2262008-02-11 04:20:54 +0000623 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
624 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000625 // FIXME: This isn't correct for methods (results in bogus warning).
626 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000627 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000628 if (CurBlock)
629 LastArg = *(CurBlock->TheDecl->param_end()-1);
630 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000631 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000632 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000633 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 SecondArgIsLastNamedArgument = PV == LastArg;
635 }
636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner30ce3442007-12-19 23:59:04 +0000638 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000639 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000640 diag::warn_second_parameter_of_va_start_not_last_named_argument);
641 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000642}
Chris Lattner30ce3442007-12-19 23:59:04 +0000643
Chris Lattner1b9a0792007-12-20 00:26:33 +0000644/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
645/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000646bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
647 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000648 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000649 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000650 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000651 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000653 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 << SourceRange(TheCall->getArg(2)->getLocStart(),
655 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000656
John Wiegley429bb272011-04-08 18:41:53 +0000657 ExprResult OrigArg0 = TheCall->getArg(0);
658 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000659
Chris Lattner1b9a0792007-12-20 00:26:33 +0000660 // Do standard promotions between the two arguments, returning their common
661 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000662 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000663 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
664 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000665
666 // Make sure any conversions are pushed back into the call; this is
667 // type safe since unordered compare builtins are declared as "_Bool
668 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000669 TheCall->setArg(0, OrigArg0.get());
670 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000671
John Wiegley429bb272011-04-08 18:41:53 +0000672 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000673 return false;
674
Chris Lattner1b9a0792007-12-20 00:26:33 +0000675 // If the common type isn't a real floating type, then the arguments were
676 // invalid for this operation.
677 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000678 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000680 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
681 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattner1b9a0792007-12-20 00:26:33 +0000683 return false;
684}
685
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000686/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
687/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000688/// to check everything. We expect the last argument to be a floating point
689/// value.
690bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
691 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000692 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000693 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000694 if (TheCall->getNumArgs() > NumArgs)
695 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000696 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000697 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000698 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000699 (*(TheCall->arg_end()-1))->getLocEnd());
700
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000701 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Eli Friedman9ac6f622009-08-31 20:06:00 +0000703 if (OrigArg->isTypeDependent())
704 return false;
705
Chris Lattner81368fb2010-05-06 05:50:07 +0000706 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000707 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000708 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000709 diag::err_typecheck_call_invalid_unary_fp)
710 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner81368fb2010-05-06 05:50:07 +0000712 // If this is an implicit conversion from float -> double, remove it.
713 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
714 Expr *CastArg = Cast->getSubExpr();
715 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
716 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
717 "promotion from float to double is the only expected cast here");
718 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000719 TheCall->setArg(NumArgs-1, CastArg);
720 OrigArg = CastArg;
721 }
722 }
723
Eli Friedman9ac6f622009-08-31 20:06:00 +0000724 return false;
725}
726
Eli Friedmand38617c2008-05-14 19:38:39 +0000727/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
728// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000729ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000730 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000731 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000732 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000733 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000734 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000735
Nate Begeman37b6a572010-06-08 00:16:34 +0000736 // Determine which of the following types of shufflevector we're checking:
737 // 1) unary, vector mask: (lhs, mask)
738 // 2) binary, vector mask: (lhs, rhs, mask)
739 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
740 QualType resType = TheCall->getArg(0)->getType();
741 unsigned numElements = 0;
742
Douglas Gregorcde01732009-05-19 22:10:17 +0000743 if (!TheCall->getArg(0)->isTypeDependent() &&
744 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000745 QualType LHSType = TheCall->getArg(0)->getType();
746 QualType RHSType = TheCall->getArg(1)->getType();
747
748 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000749 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000750 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000751 TheCall->getArg(1)->getLocEnd());
752 return ExprError();
753 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000754
755 numElements = LHSType->getAs<VectorType>()->getNumElements();
756 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Nate Begeman37b6a572010-06-08 00:16:34 +0000758 // Check to see if we have a call with 2 vector arguments, the unary shuffle
759 // with mask. If so, verify that RHS is an integer vector type with the
760 // same number of elts as lhs.
761 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000762 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000763 RHSType->getAs<VectorType>()->getNumElements() != numElements)
764 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
765 << SourceRange(TheCall->getArg(1)->getLocStart(),
766 TheCall->getArg(1)->getLocEnd());
767 numResElements = numElements;
768 }
769 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000770 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000771 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000772 TheCall->getArg(1)->getLocEnd());
773 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000774 } else if (numElements != numResElements) {
775 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000776 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000777 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000779 }
780
781 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000782 if (TheCall->getArg(i)->isTypeDependent() ||
783 TheCall->getArg(i)->isValueDependent())
784 continue;
785
Nate Begeman37b6a572010-06-08 00:16:34 +0000786 llvm::APSInt Result(32);
787 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
788 return ExprError(Diag(TheCall->getLocStart(),
789 diag::err_shufflevector_nonconstant_argument)
790 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000791
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000792 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000793 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000794 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000795 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000796 }
797
798 llvm::SmallVector<Expr*, 32> exprs;
799
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000800 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000801 exprs.push_back(TheCall->getArg(i));
802 TheCall->setArg(i, 0);
803 }
804
Nate Begemana88dc302009-08-12 02:10:25 +0000805 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000806 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000807 TheCall->getCallee()->getLocStart(),
808 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000809}
Chris Lattner30ce3442007-12-19 23:59:04 +0000810
Daniel Dunbar4493f792008-07-21 22:59:13 +0000811/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
812// This is declared to take (const void*, ...) and can take two
813// optional constant int args.
814bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000815 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000816
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000817 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000818 return Diag(TheCall->getLocEnd(),
819 diag::err_typecheck_call_too_many_args_at_most)
820 << 0 /*function call*/ << 3 << NumArgs
821 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000822
823 // Argument 0 is checked for us and the remaining arguments must be
824 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000825 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000826 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000827
Eli Friedman9aef7262009-12-04 00:30:06 +0000828 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000829 if (SemaBuiltinConstantArg(TheCall, i, Result))
830 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Daniel Dunbar4493f792008-07-21 22:59:13 +0000832 // FIXME: gcc issues a warning and rewrites these to 0. These
833 // seems especially odd for the third argument since the default
834 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000835 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000836 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000837 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000838 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000839 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000840 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000842 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000843 }
844 }
845
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000846 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000847}
848
Eric Christopher691ebc32010-04-17 02:26:23 +0000849/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
850/// TheCall is a constant expression.
851bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
852 llvm::APSInt &Result) {
853 Expr *Arg = TheCall->getArg(ArgNum);
854 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
855 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
856
857 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
858
859 if (!Arg->isIntegerConstantExpr(Result, Context))
860 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000861 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000862
Chris Lattner21fb98e2009-09-23 06:06:36 +0000863 return false;
864}
865
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000866/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
867/// int type). This simply type checks that type is one of the defined
868/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000869// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000870bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000871 llvm::APSInt Result;
872
873 // Check constant-ness first.
874 if (SemaBuiltinConstantArg(TheCall, 1, Result))
875 return true;
876
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000877 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000878 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000879 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
880 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000881 }
882
883 return false;
884}
885
Eli Friedman586d6a82009-05-03 06:04:26 +0000886/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000887/// This checks that val is a constant 1.
888bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
889 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000890 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000891
Eric Christopher691ebc32010-04-17 02:26:23 +0000892 // TODO: This is less than ideal. Overload this to take a value.
893 if (SemaBuiltinConstantArg(TheCall, 1, Result))
894 return true;
895
896 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000897 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
898 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
899
900 return false;
901}
902
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000903// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000904bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
905 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000906 unsigned format_idx, unsigned firstDataArg,
907 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000908 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000909 if (E->isTypeDependent() || E->isValueDependent())
910 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000911
Peter Collingbournef111d932011-04-15 00:35:48 +0000912 E = E->IgnoreParens();
913
Ted Kremenekd30ef872009-01-12 23:09:09 +0000914 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000915 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000916 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000917 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000918 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
919 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000920 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000921 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000922 }
923
Ted Kremenek95355bb2010-09-09 03:51:42 +0000924 case Stmt::IntegerLiteralClass:
925 // Technically -Wformat-nonliteral does not warn about this case.
926 // The behavior of printf and friends in this case is implementation
927 // dependent. Ideally if the format string cannot be null then
928 // it should have a 'nonnull' attribute in the function prototype.
929 return true;
930
Ted Kremenekd30ef872009-01-12 23:09:09 +0000931 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000932 E = cast<ImplicitCastExpr>(E)->getSubExpr();
933 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000934 }
935
John McCall56ca35d2011-02-17 10:25:35 +0000936 case Stmt::OpaqueValueExprClass:
937 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
938 E = src;
939 goto tryAgain;
940 }
941 return false;
942
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000943 case Stmt::PredefinedExprClass:
944 // While __func__, etc., are technically not string literals, they
945 // cannot contain format specifiers and thus are not a security
946 // liability.
947 return true;
948
Ted Kremenek082d9362009-03-20 21:35:28 +0000949 case Stmt::DeclRefExprClass: {
950 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Ted Kremenek082d9362009-03-20 21:35:28 +0000952 // As an exception, do not flag errors for variables binding to
953 // const string literals.
954 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
955 bool isConstant = false;
956 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000957
Ted Kremenek082d9362009-03-20 21:35:28 +0000958 if (const ArrayType *AT = Context.getAsArrayType(T)) {
959 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000960 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000961 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000962 PT->getPointeeType().isConstant(Context);
963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Ted Kremenek082d9362009-03-20 21:35:28 +0000965 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000966 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000967 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000968 HasVAListArg, format_idx, firstDataArg,
969 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Anders Carlssond966a552009-06-28 19:55:58 +0000972 // For vprintf* functions (i.e., HasVAListArg==true), we add a
973 // special check to see if the format string is a function parameter
974 // of the function calling the printf function. If the function
975 // has an attribute indicating it is a printf-like function, then we
976 // should suppress warnings concerning non-literals being used in a call
977 // to a vprintf function. For example:
978 //
979 // void
980 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
981 // va_list ap;
982 // va_start(ap, fmt);
983 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
984 // ...
985 //
986 //
987 // FIXME: We don't have full attribute support yet, so just check to see
988 // if the argument is a DeclRefExpr that references a parameter. We'll
989 // add proper support for checking the attribute later.
990 if (HasVAListArg)
991 if (isa<ParmVarDecl>(VD))
992 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Ted Kremenek082d9362009-03-20 21:35:28 +0000995 return false;
996 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000997
Anders Carlsson8f031b32009-06-27 04:05:33 +0000998 case Stmt::CallExprClass: {
999 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001000 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001001 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1003 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001004 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001005 unsigned ArgIndex = FA->getFormatIdx();
1006 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
1008 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001009 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001010 }
1011 }
1012 }
1013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Anders Carlsson8f031b32009-06-27 04:05:33 +00001015 return false;
1016 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 case Stmt::ObjCStringLiteralClass:
1018 case Stmt::StringLiteralClass: {
1019 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Ted Kremenek082d9362009-03-20 21:35:28 +00001021 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001022 StrE = ObjCFExpr->getString();
1023 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001024 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Ted Kremenekd30ef872009-01-12 23:09:09 +00001026 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001027 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1028 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001029 return true;
1030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Ted Kremenekd30ef872009-01-12 23:09:09 +00001032 return false;
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Ted Kremenek082d9362009-03-20 21:35:28 +00001035 default:
1036 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001037 }
1038}
1039
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001040void
Mike Stump1eb44332009-09-09 15:08:12 +00001041Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001042 const Expr * const *ExprArgs,
1043 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001044 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1045 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001046 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001047 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001048 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001049 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001050 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001051 }
1052}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001053
Ted Kremenek826a3452010-07-16 02:11:22 +00001054/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1055/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001056void
Ted Kremenek826a3452010-07-16 02:11:22 +00001057Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1058 unsigned format_idx, unsigned firstDataArg,
1059 bool isPrintf) {
1060
Ted Kremenek082d9362009-03-20 21:35:28 +00001061 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001062
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001063 // The way the format attribute works in GCC, the implicit this argument
1064 // of member functions is counted. However, it doesn't appear in our own
1065 // lists, so decrement format_idx in that case.
1066 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001067 const CXXMethodDecl *method_decl =
1068 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1069 if (method_decl && method_decl->isInstance()) {
1070 // Catch a format attribute mistakenly referring to the object argument.
1071 if (format_idx == 0)
1072 return;
1073 --format_idx;
1074 if(firstDataArg != 0)
1075 --firstDataArg;
1076 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001077 }
1078
Ted Kremenek826a3452010-07-16 02:11:22 +00001079 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001080 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001081 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001082 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001083 return;
1084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Ted Kremenek082d9362009-03-20 21:35:28 +00001086 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner59907c42007-08-10 20:18:51 +00001088 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001089 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001090 // Dynamically generated format strings are difficult to
1091 // automatically vet at compile time. Requiring that format strings
1092 // are string literals: (1) permits the checking of format strings by
1093 // the compiler and thereby (2) can practically remove the source of
1094 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001095
Mike Stump1eb44332009-09-09 15:08:12 +00001096 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001097 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001098 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001099 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001100 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001101 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001102 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001103
Chris Lattner655f1412009-04-29 04:59:47 +00001104 // If there are no arguments specified, warn with -Wformat-security, otherwise
1105 // warn only with -Wformat-nonliteral.
1106 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001107 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001108 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001109 << OrigFormatExpr->getSourceRange();
1110 else
Mike Stump1eb44332009-09-09 15:08:12 +00001111 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001112 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001113 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001114}
Ted Kremenek71895b92007-08-14 17:39:48 +00001115
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001117class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1118protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001119 Sema &S;
1120 const StringLiteral *FExpr;
1121 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001122 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001123 const unsigned NumDataArgs;
1124 const bool IsObjCLiteral;
1125 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001126 const bool HasVAListArg;
1127 const CallExpr *TheCall;
1128 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001129 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001130 bool usesPositionalArgs;
1131 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001132public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001133 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001134 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001135 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001136 const char *beg, bool hasVAListArg,
1137 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001138 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001139 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001140 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001141 IsObjCLiteral(isObjCLiteral), Beg(beg),
1142 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001143 TheCall(theCall), FormatIdx(formatIdx),
1144 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001145 CoveredArgs.resize(numDataArgs);
1146 CoveredArgs.reset();
1147 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001148
Ted Kremenek07d161f2010-01-29 01:50:07 +00001149 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001150
Ted Kremenek826a3452010-07-16 02:11:22 +00001151 void HandleIncompleteSpecifier(const char *startSpecifier,
1152 unsigned specifierLen);
1153
Ted Kremenekefaff192010-02-27 01:41:03 +00001154 virtual void HandleInvalidPosition(const char *startSpecifier,
1155 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001156 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001157
1158 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1159
Ted Kremeneke0e53132010-01-28 23:39:18 +00001160 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001161
Ted Kremenek826a3452010-07-16 02:11:22 +00001162protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001163 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1164 const char *startSpec,
1165 unsigned specifierLen,
1166 const char *csStart, unsigned csLen);
1167
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001168 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001169 CharSourceRange getSpecifierRange(const char *startSpecifier,
1170 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001171 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001172
Ted Kremenek0d277352010-01-29 01:06:55 +00001173 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001174
1175 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1176 const analyze_format_string::ConversionSpecifier &CS,
1177 const char *startSpecifier, unsigned specifierLen,
1178 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001179};
1180}
1181
Ted Kremenek826a3452010-07-16 02:11:22 +00001182SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001183 return OrigFormatExpr->getSourceRange();
1184}
1185
Ted Kremenek826a3452010-07-16 02:11:22 +00001186CharSourceRange CheckFormatHandler::
1187getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001188 SourceLocation Start = getLocationOfByte(startSpecifier);
1189 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1190
1191 // Advance the end SourceLocation by one due to half-open ranges.
1192 End = End.getFileLocWithOffset(1);
1193
1194 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001195}
1196
Ted Kremenek826a3452010-07-16 02:11:22 +00001197SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001198 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001199}
1200
Ted Kremenek826a3452010-07-16 02:11:22 +00001201void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1202 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001203 SourceLocation Loc = getLocationOfByte(startSpecifier);
1204 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001205 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001206}
1207
Ted Kremenekefaff192010-02-27 01:41:03 +00001208void
Ted Kremenek826a3452010-07-16 02:11:22 +00001209CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1210 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001211 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001212 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1213 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001214}
1215
Ted Kremenek826a3452010-07-16 02:11:22 +00001216void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001217 unsigned posLen) {
1218 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001219 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1220 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001221}
1222
Ted Kremenek826a3452010-07-16 02:11:22 +00001223void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001224 if (!IsObjCLiteral) {
1225 // The presence of a null character is likely an error.
1226 S.Diag(getLocationOfByte(nullCharacter),
1227 diag::warn_printf_format_string_contains_null_char)
1228 << getFormatStringRange();
1229 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001230}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001231
Ted Kremenek826a3452010-07-16 02:11:22 +00001232const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1233 return TheCall->getArg(FirstDataArg + i);
1234}
1235
1236void CheckFormatHandler::DoneProcessing() {
1237 // Does the number of data arguments exceed the number of
1238 // format conversions in the format string?
1239 if (!HasVAListArg) {
1240 // Find any arguments that weren't covered.
1241 CoveredArgs.flip();
1242 signed notCoveredArg = CoveredArgs.find_first();
1243 if (notCoveredArg >= 0) {
1244 assert((unsigned)notCoveredArg < NumDataArgs);
1245 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1246 diag::warn_printf_data_arg_not_used)
1247 << getFormatStringRange();
1248 }
1249 }
1250}
1251
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001252bool
1253CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1254 SourceLocation Loc,
1255 const char *startSpec,
1256 unsigned specifierLen,
1257 const char *csStart,
1258 unsigned csLen) {
1259
1260 bool keepGoing = true;
1261 if (argIndex < NumDataArgs) {
1262 // Consider the argument coverered, even though the specifier doesn't
1263 // make sense.
1264 CoveredArgs.set(argIndex);
1265 }
1266 else {
1267 // If argIndex exceeds the number of data arguments we
1268 // don't issue a warning because that is just a cascade of warnings (and
1269 // they may have intended '%%' anyway). We don't want to continue processing
1270 // the format string after this point, however, as we will like just get
1271 // gibberish when trying to match arguments.
1272 keepGoing = false;
1273 }
1274
1275 S.Diag(Loc, diag::warn_format_invalid_conversion)
1276 << llvm::StringRef(csStart, csLen)
1277 << getSpecifierRange(startSpec, specifierLen);
1278
1279 return keepGoing;
1280}
1281
Ted Kremenek666a1972010-07-26 19:45:42 +00001282bool
1283CheckFormatHandler::CheckNumArgs(
1284 const analyze_format_string::FormatSpecifier &FS,
1285 const analyze_format_string::ConversionSpecifier &CS,
1286 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1287
1288 if (argIndex >= NumDataArgs) {
1289 if (FS.usesPositionalArg()) {
1290 S.Diag(getLocationOfByte(CS.getStart()),
1291 diag::warn_printf_positional_arg_exceeds_data_args)
1292 << (argIndex+1) << NumDataArgs
1293 << getSpecifierRange(startSpecifier, specifierLen);
1294 }
1295 else {
1296 S.Diag(getLocationOfByte(CS.getStart()),
1297 diag::warn_printf_insufficient_data_args)
1298 << getSpecifierRange(startSpecifier, specifierLen);
1299 }
1300
1301 return false;
1302 }
1303 return true;
1304}
1305
Ted Kremenek826a3452010-07-16 02:11:22 +00001306//===--- CHECK: Printf format string checking ------------------------------===//
1307
1308namespace {
1309class CheckPrintfHandler : public CheckFormatHandler {
1310public:
1311 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1312 const Expr *origFormatExpr, unsigned firstDataArg,
1313 unsigned numDataArgs, bool isObjCLiteral,
1314 const char *beg, bool hasVAListArg,
1315 const CallExpr *theCall, unsigned formatIdx)
1316 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1317 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1318 theCall, formatIdx) {}
1319
1320
1321 bool HandleInvalidPrintfConversionSpecifier(
1322 const analyze_printf::PrintfSpecifier &FS,
1323 const char *startSpecifier,
1324 unsigned specifierLen);
1325
1326 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1327 const char *startSpecifier,
1328 unsigned specifierLen);
1329
1330 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1331 const char *startSpecifier, unsigned specifierLen);
1332 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1333 const analyze_printf::OptionalAmount &Amt,
1334 unsigned type,
1335 const char *startSpecifier, unsigned specifierLen);
1336 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1337 const analyze_printf::OptionalFlag &flag,
1338 const char *startSpecifier, unsigned specifierLen);
1339 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1340 const analyze_printf::OptionalFlag &ignoredFlag,
1341 const analyze_printf::OptionalFlag &flag,
1342 const char *startSpecifier, unsigned specifierLen);
1343};
1344}
1345
1346bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1347 const analyze_printf::PrintfSpecifier &FS,
1348 const char *startSpecifier,
1349 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001350 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001351 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001352
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001353 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1354 getLocationOfByte(CS.getStart()),
1355 startSpecifier, specifierLen,
1356 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001357}
1358
Ted Kremenek826a3452010-07-16 02:11:22 +00001359bool CheckPrintfHandler::HandleAmount(
1360 const analyze_format_string::OptionalAmount &Amt,
1361 unsigned k, const char *startSpecifier,
1362 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001363
1364 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001365 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001366 unsigned argIndex = Amt.getArgIndex();
1367 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001368 S.Diag(getLocationOfByte(Amt.getStart()),
1369 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001370 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001371 // Don't do any more checking. We will just emit
1372 // spurious errors.
1373 return false;
1374 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001375
Ted Kremenek0d277352010-01-29 01:06:55 +00001376 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001377 // Although not in conformance with C99, we also allow the argument to be
1378 // an 'unsigned int' as that is a reasonably safe case. GCC also
1379 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001380 CoveredArgs.set(argIndex);
1381 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001382 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001383
1384 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1385 assert(ATR.isValid());
1386
1387 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001388 S.Diag(getLocationOfByte(Amt.getStart()),
1389 diag::warn_printf_asterisk_wrong_type)
1390 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001391 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001392 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001393 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001394 // Don't do any more checking. We will just emit
1395 // spurious errors.
1396 return false;
1397 }
1398 }
1399 }
1400 return true;
1401}
Ted Kremenek0d277352010-01-29 01:06:55 +00001402
Tom Caree4ee9662010-06-17 19:00:27 +00001403void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001404 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001405 const analyze_printf::OptionalAmount &Amt,
1406 unsigned type,
1407 const char *startSpecifier,
1408 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001409 const analyze_printf::PrintfConversionSpecifier &CS =
1410 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001411 switch (Amt.getHowSpecified()) {
1412 case analyze_printf::OptionalAmount::Constant:
1413 S.Diag(getLocationOfByte(Amt.getStart()),
1414 diag::warn_printf_nonsensical_optional_amount)
1415 << type
1416 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001417 << getSpecifierRange(startSpecifier, specifierLen)
1418 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001419 Amt.getConstantLength()));
1420 break;
1421
1422 default:
1423 S.Diag(getLocationOfByte(Amt.getStart()),
1424 diag::warn_printf_nonsensical_optional_amount)
1425 << type
1426 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001427 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001428 break;
1429 }
1430}
1431
Ted Kremenek826a3452010-07-16 02:11:22 +00001432void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001433 const analyze_printf::OptionalFlag &flag,
1434 const char *startSpecifier,
1435 unsigned specifierLen) {
1436 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001437 const analyze_printf::PrintfConversionSpecifier &CS =
1438 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001439 S.Diag(getLocationOfByte(flag.getPosition()),
1440 diag::warn_printf_nonsensical_flag)
1441 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001442 << getSpecifierRange(startSpecifier, specifierLen)
1443 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001444}
1445
1446void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001447 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001448 const analyze_printf::OptionalFlag &ignoredFlag,
1449 const analyze_printf::OptionalFlag &flag,
1450 const char *startSpecifier,
1451 unsigned specifierLen) {
1452 // Warn about ignored flag with a fixit removal.
1453 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1454 diag::warn_printf_ignored_flag)
1455 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001456 << getSpecifierRange(startSpecifier, specifierLen)
1457 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001458 ignoredFlag.getPosition(), 1));
1459}
1460
Ted Kremeneke0e53132010-01-28 23:39:18 +00001461bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001462CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001463 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001464 const char *startSpecifier,
1465 unsigned specifierLen) {
1466
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001467 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001468 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001469 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001470
Ted Kremenekbaa40062010-07-19 22:01:06 +00001471 if (FS.consumesDataArgument()) {
1472 if (atFirstArg) {
1473 atFirstArg = false;
1474 usesPositionalArgs = FS.usesPositionalArg();
1475 }
1476 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1477 // Cannot mix-and-match positional and non-positional arguments.
1478 S.Diag(getLocationOfByte(CS.getStart()),
1479 diag::warn_format_mix_positional_nonpositional_args)
1480 << getSpecifierRange(startSpecifier, specifierLen);
1481 return false;
1482 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001483 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001484
Ted Kremenekefaff192010-02-27 01:41:03 +00001485 // First check if the field width, precision, and conversion specifier
1486 // have matching data arguments.
1487 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1488 startSpecifier, specifierLen)) {
1489 return false;
1490 }
1491
1492 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1493 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001494 return false;
1495 }
1496
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001497 if (!CS.consumesDataArgument()) {
1498 // FIXME: Technically specifying a precision or field width here
1499 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001500 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001501 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001502
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001503 // Consume the argument.
1504 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001505 if (argIndex < NumDataArgs) {
1506 // The check to see if the argIndex is valid will come later.
1507 // We set the bit here because we may exit early from this
1508 // function if we encounter some other error.
1509 CoveredArgs.set(argIndex);
1510 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001511
1512 // Check for using an Objective-C specific conversion specifier
1513 // in a non-ObjC literal.
1514 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001515 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1516 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001517 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001518
Tom Caree4ee9662010-06-17 19:00:27 +00001519 // Check for invalid use of field width
1520 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001521 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001522 startSpecifier, specifierLen);
1523 }
1524
1525 // Check for invalid use of precision
1526 if (!FS.hasValidPrecision()) {
1527 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1528 startSpecifier, specifierLen);
1529 }
1530
1531 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001532 if (!FS.hasValidThousandsGroupingPrefix())
1533 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001534 if (!FS.hasValidLeadingZeros())
1535 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1536 if (!FS.hasValidPlusPrefix())
1537 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001538 if (!FS.hasValidSpacePrefix())
1539 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001540 if (!FS.hasValidAlternativeForm())
1541 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1542 if (!FS.hasValidLeftJustified())
1543 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1544
1545 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001546 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1547 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1548 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001549 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1550 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1551 startSpecifier, specifierLen);
1552
1553 // Check the length modifier is valid with the given conversion specifier.
1554 const LengthModifier &LM = FS.getLengthModifier();
1555 if (!FS.hasValidLengthModifier())
1556 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001557 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001558 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001559 << getSpecifierRange(startSpecifier, specifierLen)
1560 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001561 LM.getLength()));
1562
1563 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001564 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001565 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001566 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001567 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001568 // Continue checking the other format specifiers.
1569 return true;
1570 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001571
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001572 // The remaining checks depend on the data arguments.
1573 if (HasVAListArg)
1574 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001575
Ted Kremenek666a1972010-07-26 19:45:42 +00001576 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001577 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001578
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001579 // Now type check the data expression that matches the
1580 // format specifier.
1581 const Expr *Ex = getDataArg(argIndex);
1582 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1583 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1584 // Check if we didn't match because of an implicit cast from a 'char'
1585 // or 'short' to an 'int'. This is done because printf is a varargs
1586 // function.
1587 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001588 if (ICE->getType() == S.Context.IntTy) {
1589 // All further checking is done on the subexpression.
1590 Ex = ICE->getSubExpr();
1591 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001592 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001593 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001594
1595 // We may be able to offer a FixItHint if it is a supported type.
1596 PrintfSpecifier fixedFS = FS;
1597 bool success = fixedFS.fixType(Ex->getType());
1598
1599 if (success) {
1600 // Get the fix string from the fixed format specifier
1601 llvm::SmallString<128> buf;
1602 llvm::raw_svector_ostream os(buf);
1603 fixedFS.toString(os);
1604
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001605 // FIXME: getRepresentativeType() perhaps should return a string
1606 // instead of a QualType to better handle when the representative
1607 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001608 S.Diag(getLocationOfByte(CS.getStart()),
1609 diag::warn_printf_conversion_argument_type_mismatch)
1610 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1611 << getSpecifierRange(startSpecifier, specifierLen)
1612 << Ex->getSourceRange()
1613 << FixItHint::CreateReplacement(
1614 getSpecifierRange(startSpecifier, specifierLen),
1615 os.str());
1616 }
1617 else {
1618 S.Diag(getLocationOfByte(CS.getStart()),
1619 diag::warn_printf_conversion_argument_type_mismatch)
1620 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1621 << getSpecifierRange(startSpecifier, specifierLen)
1622 << Ex->getSourceRange();
1623 }
1624 }
1625
Ted Kremeneke0e53132010-01-28 23:39:18 +00001626 return true;
1627}
1628
Ted Kremenek826a3452010-07-16 02:11:22 +00001629//===--- CHECK: Scanf format string checking ------------------------------===//
1630
1631namespace {
1632class CheckScanfHandler : public CheckFormatHandler {
1633public:
1634 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1635 const Expr *origFormatExpr, unsigned firstDataArg,
1636 unsigned numDataArgs, bool isObjCLiteral,
1637 const char *beg, bool hasVAListArg,
1638 const CallExpr *theCall, unsigned formatIdx)
1639 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1640 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1641 theCall, formatIdx) {}
1642
1643 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1644 const char *startSpecifier,
1645 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001646
1647 bool HandleInvalidScanfConversionSpecifier(
1648 const analyze_scanf::ScanfSpecifier &FS,
1649 const char *startSpecifier,
1650 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001651
1652 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001653};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001654}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001655
Ted Kremenekb7c21012010-07-16 18:28:03 +00001656void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1657 const char *end) {
1658 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1659 << getSpecifierRange(start, end - start);
1660}
1661
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001662bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1663 const analyze_scanf::ScanfSpecifier &FS,
1664 const char *startSpecifier,
1665 unsigned specifierLen) {
1666
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001667 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001668 FS.getConversionSpecifier();
1669
1670 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1671 getLocationOfByte(CS.getStart()),
1672 startSpecifier, specifierLen,
1673 CS.getStart(), CS.getLength());
1674}
1675
Ted Kremenek826a3452010-07-16 02:11:22 +00001676bool CheckScanfHandler::HandleScanfSpecifier(
1677 const analyze_scanf::ScanfSpecifier &FS,
1678 const char *startSpecifier,
1679 unsigned specifierLen) {
1680
1681 using namespace analyze_scanf;
1682 using namespace analyze_format_string;
1683
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001684 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001685
Ted Kremenekbaa40062010-07-19 22:01:06 +00001686 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1687 // be used to decide if we are using positional arguments consistently.
1688 if (FS.consumesDataArgument()) {
1689 if (atFirstArg) {
1690 atFirstArg = false;
1691 usesPositionalArgs = FS.usesPositionalArg();
1692 }
1693 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1694 // Cannot mix-and-match positional and non-positional arguments.
1695 S.Diag(getLocationOfByte(CS.getStart()),
1696 diag::warn_format_mix_positional_nonpositional_args)
1697 << getSpecifierRange(startSpecifier, specifierLen);
1698 return false;
1699 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001700 }
1701
1702 // Check if the field with is non-zero.
1703 const OptionalAmount &Amt = FS.getFieldWidth();
1704 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1705 if (Amt.getConstantAmount() == 0) {
1706 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1707 Amt.getConstantLength());
1708 S.Diag(getLocationOfByte(Amt.getStart()),
1709 diag::warn_scanf_nonzero_width)
1710 << R << FixItHint::CreateRemoval(R);
1711 }
1712 }
1713
1714 if (!FS.consumesDataArgument()) {
1715 // FIXME: Technically specifying a precision or field width here
1716 // makes no sense. Worth issuing a warning at some point.
1717 return true;
1718 }
1719
1720 // Consume the argument.
1721 unsigned argIndex = FS.getArgIndex();
1722 if (argIndex < NumDataArgs) {
1723 // The check to see if the argIndex is valid will come later.
1724 // We set the bit here because we may exit early from this
1725 // function if we encounter some other error.
1726 CoveredArgs.set(argIndex);
1727 }
1728
Ted Kremenek1e51c202010-07-20 20:04:47 +00001729 // Check the length modifier is valid with the given conversion specifier.
1730 const LengthModifier &LM = FS.getLengthModifier();
1731 if (!FS.hasValidLengthModifier()) {
1732 S.Diag(getLocationOfByte(LM.getStart()),
1733 diag::warn_format_nonsensical_length)
1734 << LM.toString() << CS.toString()
1735 << getSpecifierRange(startSpecifier, specifierLen)
1736 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1737 LM.getLength()));
1738 }
1739
Ted Kremenek826a3452010-07-16 02:11:22 +00001740 // The remaining checks depend on the data arguments.
1741 if (HasVAListArg)
1742 return true;
1743
Ted Kremenek666a1972010-07-26 19:45:42 +00001744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001746
1747 // FIXME: Check that the argument type matches the format specifier.
1748
1749 return true;
1750}
1751
1752void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001753 const Expr *OrigFormatExpr,
1754 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001755 unsigned format_idx, unsigned firstDataArg,
1756 bool isPrintf) {
1757
Ted Kremeneke0e53132010-01-28 23:39:18 +00001758 // CHECK: is the format string a wide literal?
1759 if (FExpr->isWide()) {
1760 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001761 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001762 << OrigFormatExpr->getSourceRange();
1763 return;
1764 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001765
Ted Kremeneke0e53132010-01-28 23:39:18 +00001766 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001767 llvm::StringRef StrRef = FExpr->getString();
1768 const char *Str = StrRef.data();
1769 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001770
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001772 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001773 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001774 << OrigFormatExpr->getSourceRange();
1775 return;
1776 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001777
1778 if (isPrintf) {
1779 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1780 TheCall->getNumArgs() - firstDataArg,
1781 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1782 HasVAListArg, TheCall, format_idx);
1783
1784 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1785 H.DoneProcessing();
1786 }
1787 else {
1788 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1789 TheCall->getNumArgs() - firstDataArg,
1790 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1791 HasVAListArg, TheCall, format_idx);
1792
1793 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1794 H.DoneProcessing();
1795 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001796}
1797
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001798//===--- CHECK: Standard memory functions ---------------------------------===//
1799
1800/// \brief Check for dangerous or invalid arguments to memset().
1801///
1802/// This issues warnings on known problematic or dangerous or unspecified
1803/// arguments to the standard 'memset' function call.
1804///
1805/// \param Call The call expression to diagnose.
1806void Sema::CheckMemsetArguments(const CallExpr *Call) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001807 // It is possible to have a non-standard definition of memset. Validate
1808 // we have the proper number of arguments, and if not, abort further
1809 // checking.
1810 if (Call->getNumArgs() != 3)
1811 return;
1812
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001813 const Expr *Dest = Call->getArg(0)->IgnoreParenImpCasts();
1814
1815 QualType DestTy = Dest->getType();
1816 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1817 QualType PointeeTy = DestPtrTy->getPointeeType();
Chandler Carruth134cb442011-04-27 18:48:59 +00001818 if (!PointeeTy->isPODType() && !PointeeTy->isVoidType()) {
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001819 DiagRuntimeBehavior(
1820 Dest->getExprLoc(), Dest,
1821 PDiag(diag::warn_non_pod_memset)
1822 << PointeeTy << Call->getCallee()->getSourceRange());
1823
1824 SourceRange ArgRange = Call->getArg(0)->getSourceRange();
1825 DiagRuntimeBehavior(
1826 Dest->getExprLoc(), Dest,
1827 PDiag(diag::note_non_pod_memset_silence)
1828 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1829 }
1830 }
1831}
1832
Ted Kremenek06de2762007-08-17 16:46:58 +00001833//===--- CHECK: Return Address of Stack Variable --------------------------===//
1834
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001835static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1836static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001837
1838/// CheckReturnStackAddr - Check if a return statement returns the address
1839/// of a stack variable.
1840void
1841Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1842 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001844 Expr *stackE = 0;
1845 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1846
1847 // Perform checking for returned stack addresses, local blocks,
1848 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001849 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001850 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001851 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001852 stackE = EvalVal(RetValExp, refVars);
1853 }
1854
1855 if (stackE == 0)
1856 return; // Nothing suspicious was found.
1857
1858 SourceLocation diagLoc;
1859 SourceRange diagRange;
1860 if (refVars.empty()) {
1861 diagLoc = stackE->getLocStart();
1862 diagRange = stackE->getSourceRange();
1863 } else {
1864 // We followed through a reference variable. 'stackE' contains the
1865 // problematic expression but we will warn at the return statement pointing
1866 // at the reference variable. We will later display the "trail" of
1867 // reference variables using notes.
1868 diagLoc = refVars[0]->getLocStart();
1869 diagRange = refVars[0]->getSourceRange();
1870 }
1871
1872 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1873 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1874 : diag::warn_ret_stack_addr)
1875 << DR->getDecl()->getDeclName() << diagRange;
1876 } else if (isa<BlockExpr>(stackE)) { // local block.
1877 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1878 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1879 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1880 } else { // local temporary.
1881 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1882 : diag::warn_ret_local_temp_addr)
1883 << diagRange;
1884 }
1885
1886 // Display the "trail" of reference variables that we followed until we
1887 // found the problematic expression using notes.
1888 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1889 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1890 // If this var binds to another reference var, show the range of the next
1891 // var, otherwise the var binds to the problematic expression, in which case
1892 // show the range of the expression.
1893 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1894 : stackE->getSourceRange();
1895 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1896 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001897 }
1898}
1899
1900/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1901/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001902/// to a location on the stack, a local block, an address of a label, or a
1903/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001904/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001905/// encounter a subexpression that (1) clearly does not lead to one of the
1906/// above problematic expressions (2) is something we cannot determine leads to
1907/// a problematic expression based on such local checking.
1908///
1909/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1910/// the expression that they point to. Such variables are added to the
1911/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001912///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001913/// EvalAddr processes expressions that are pointers that are used as
1914/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001915/// At the base case of the recursion is a check for the above problematic
1916/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001917///
1918/// This implementation handles:
1919///
1920/// * pointer-to-pointer casts
1921/// * implicit conversions from array references to pointers
1922/// * taking the address of fields
1923/// * arbitrary interplay between "&" and "*" operators
1924/// * pointer arithmetic from an address of a stack variable
1925/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001926static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1927 if (E->isTypeDependent())
1928 return NULL;
1929
Ted Kremenek06de2762007-08-17 16:46:58 +00001930 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001931 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001932 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001934 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Peter Collingbournef111d932011-04-15 00:35:48 +00001936 E = E->IgnoreParens();
1937
Ted Kremenek06de2762007-08-17 16:46:58 +00001938 // Our "symbolic interpreter" is just a dispatch off the currently
1939 // viewed AST node. We then recursively traverse the AST by calling
1940 // EvalAddr and EvalVal appropriately.
1941 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001942 case Stmt::DeclRefExprClass: {
1943 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1944
1945 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1946 // If this is a reference variable, follow through to the expression that
1947 // it points to.
1948 if (V->hasLocalStorage() &&
1949 V->getType()->isReferenceType() && V->hasInit()) {
1950 // Add the reference variable to the "trail".
1951 refVars.push_back(DR);
1952 return EvalAddr(V->getInit(), refVars);
1953 }
1954
1955 return NULL;
1956 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001957
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001958 case Stmt::UnaryOperatorClass: {
1959 // The only unary operator that make sense to handle here
1960 // is AddrOf. All others don't make sense as pointers.
1961 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001962
John McCall2de56d12010-08-25 11:45:40 +00001963 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001964 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001965 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001966 return NULL;
1967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001969 case Stmt::BinaryOperatorClass: {
1970 // Handle pointer arithmetic. All other binary operators are not valid
1971 // in this context.
1972 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001973 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001974
John McCall2de56d12010-08-25 11:45:40 +00001975 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001976 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001978 Expr *Base = B->getLHS();
1979
1980 // Determine which argument is the real pointer base. It could be
1981 // the RHS argument instead of the LHS.
1982 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001984 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001985 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001986 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001987
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001988 // For conditional operators we need to see if either the LHS or RHS are
1989 // valid DeclRefExpr*s. If one of them is valid, we return it.
1990 case Stmt::ConditionalOperatorClass: {
1991 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001993 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001994 if (Expr *lhsExpr = C->getLHS()) {
1995 // In C++, we can have a throw-expression, which has 'void' type.
1996 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001997 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001998 return LHS;
1999 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002000
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002001 // In C++, we can have a throw-expression, which has 'void' type.
2002 if (C->getRHS()->getType()->isVoidType())
2003 return NULL;
2004
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002005 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002006 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002007
2008 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002009 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002010 return E; // local block.
2011 return NULL;
2012
2013 case Stmt::AddrLabelExprClass:
2014 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Ted Kremenek54b52742008-08-07 00:49:01 +00002016 // For casts, we need to handle conversions from arrays to
2017 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002018 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002019 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002020 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002021 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002022 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Steve Naroffdd972f22008-09-05 22:11:13 +00002024 if (SubExpr->getType()->isPointerType() ||
2025 SubExpr->getType()->isBlockPointerType() ||
2026 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002027 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002028 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002029 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002030 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002031 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002034 // C++ casts. For dynamic casts, static casts, and const casts, we
2035 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002036 // through the cast. In the case the dynamic cast doesn't fail (and
2037 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002038 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002039 // FIXME: The comment about is wrong; we're not always converting
2040 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002041 // handle references to objects.
2042 case Stmt::CXXStaticCastExprClass:
2043 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002044 case Stmt::CXXConstCastExprClass:
2045 case Stmt::CXXReinterpretCastExprClass: {
2046 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002047 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002048 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002049 else
2050 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002053 // Everything else: we simply don't reason about them.
2054 default:
2055 return NULL;
2056 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002057}
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenek06de2762007-08-17 16:46:58 +00002059
2060/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2061/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002062static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002063do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002064 // We should only be called for evaluating non-pointer expressions, or
2065 // expressions with a pointer type that are not used as references but instead
2066 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Ted Kremenek06de2762007-08-17 16:46:58 +00002068 // Our "symbolic interpreter" is just a dispatch off the currently
2069 // viewed AST node. We then recursively traverse the AST by calling
2070 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002071
2072 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002073 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002074 case Stmt::ImplicitCastExprClass: {
2075 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002076 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002077 E = IE->getSubExpr();
2078 continue;
2079 }
2080 return NULL;
2081 }
2082
Douglas Gregora2813ce2009-10-23 18:54:35 +00002083 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002084 // When we hit a DeclRefExpr we are looking at code that refers to a
2085 // variable's name. If it's not a reference variable we check if it has
2086 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002087 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Ted Kremenek06de2762007-08-17 16:46:58 +00002089 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002090 if (V->hasLocalStorage()) {
2091 if (!V->getType()->isReferenceType())
2092 return DR;
2093
2094 // Reference variable, follow through to the expression that
2095 // it points to.
2096 if (V->hasInit()) {
2097 // Add the reference variable to the "trail".
2098 refVars.push_back(DR);
2099 return EvalVal(V->getInit(), refVars);
2100 }
2101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Ted Kremenek06de2762007-08-17 16:46:58 +00002103 return NULL;
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Ted Kremenek06de2762007-08-17 16:46:58 +00002106 case Stmt::UnaryOperatorClass: {
2107 // The only unary operator that make sense to handle here
2108 // is Deref. All others don't resolve to a "name." This includes
2109 // handling all sorts of rvalues passed to a unary operator.
2110 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
John McCall2de56d12010-08-25 11:45:40 +00002112 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002113 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002114
2115 return NULL;
2116 }
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Ted Kremenek06de2762007-08-17 16:46:58 +00002118 case Stmt::ArraySubscriptExprClass: {
2119 // Array subscripts are potential references to data on the stack. We
2120 // retrieve the DeclRefExpr* for the array variable if it indeed
2121 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002122 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Ted Kremenek06de2762007-08-17 16:46:58 +00002125 case Stmt::ConditionalOperatorClass: {
2126 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002127 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002128 ConditionalOperator *C = cast<ConditionalOperator>(E);
2129
Anders Carlsson39073232007-11-30 19:04:31 +00002130 // Handle the GNU extension for missing LHS.
2131 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002132 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002133 return LHS;
2134
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002135 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002136 }
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Ted Kremenek06de2762007-08-17 16:46:58 +00002138 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002139 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002140 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Ted Kremenek06de2762007-08-17 16:46:58 +00002142 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002143 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002144 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002145
2146 // Check whether the member type is itself a reference, in which case
2147 // we're not going to refer to the member, but to what the member refers to.
2148 if (M->getMemberDecl()->getType()->isReferenceType())
2149 return NULL;
2150
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002151 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002152 }
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Ted Kremenek06de2762007-08-17 16:46:58 +00002154 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002155 // Check that we don't return or take the address of a reference to a
2156 // temporary. This is only useful in C++.
2157 if (!E->isTypeDependent() && E->isRValue())
2158 return E;
2159
2160 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002161 return NULL;
2162 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002163} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002164}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002165
2166//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2167
2168/// Check for comparisons of floating point operands using != and ==.
2169/// Issue a warning if these are no self-comparisons, as they are not likely
2170/// to do what the programmer intended.
2171void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2172 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002173
John McCallf6a16482010-12-04 03:47:34 +00002174 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2175 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002176
2177 // Special case: check for x == x (which is OK).
2178 // Do not emit warnings for such cases.
2179 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2180 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2181 if (DRL->getDecl() == DRR->getDecl())
2182 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
2184
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002185 // Special case: check for comparisons against literals that can be exactly
2186 // represented by APFloat. In such cases, do not emit a warning. This
2187 // is a heuristic: often comparison against such literals are used to
2188 // detect if a value in a variable has not changed. This clearly can
2189 // lead to false negatives.
2190 if (EmitWarning) {
2191 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2192 if (FLL->isExact())
2193 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002194 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002195 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2196 if (FLR->isExact())
2197 EmitWarning = false;
2198 }
2199 }
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002201 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002202 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002203 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002204 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002205 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Sebastian Redl0eb23302009-01-19 00:08:26 +00002207 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002208 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002209 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002210 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002212 // Emit the diagnostic.
2213 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002214 Diag(loc, diag::warn_floatingpoint_eq)
2215 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002216}
John McCallba26e582010-01-04 23:21:16 +00002217
John McCallf2370c92010-01-06 05:24:50 +00002218//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2219//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002220
John McCallf2370c92010-01-06 05:24:50 +00002221namespace {
John McCallba26e582010-01-04 23:21:16 +00002222
John McCallf2370c92010-01-06 05:24:50 +00002223/// Structure recording the 'active' range of an integer-valued
2224/// expression.
2225struct IntRange {
2226 /// The number of bits active in the int.
2227 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002228
John McCallf2370c92010-01-06 05:24:50 +00002229 /// True if the int is known not to have negative values.
2230 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002231
John McCallf2370c92010-01-06 05:24:50 +00002232 IntRange(unsigned Width, bool NonNegative)
2233 : Width(Width), NonNegative(NonNegative)
2234 {}
John McCallba26e582010-01-04 23:21:16 +00002235
John McCall1844a6e2010-11-10 23:38:19 +00002236 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002237 static IntRange forBoolType() {
2238 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002239 }
2240
John McCall1844a6e2010-11-10 23:38:19 +00002241 /// Returns the range of an opaque value of the given integral type.
2242 static IntRange forValueOfType(ASTContext &C, QualType T) {
2243 return forValueOfCanonicalType(C,
2244 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002245 }
2246
John McCall1844a6e2010-11-10 23:38:19 +00002247 /// Returns the range of an opaque value of a canonical integral type.
2248 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002249 assert(T->isCanonicalUnqualified());
2250
2251 if (const VectorType *VT = dyn_cast<VectorType>(T))
2252 T = VT->getElementType().getTypePtr();
2253 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2254 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002255
John McCall091f23f2010-11-09 22:22:12 +00002256 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002257 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2258 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002259 if (!Enum->isDefinition())
2260 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2261
John McCall323ed742010-05-06 08:58:33 +00002262 unsigned NumPositive = Enum->getNumPositiveBits();
2263 unsigned NumNegative = Enum->getNumNegativeBits();
2264
2265 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2266 }
John McCallf2370c92010-01-06 05:24:50 +00002267
2268 const BuiltinType *BT = cast<BuiltinType>(T);
2269 assert(BT->isInteger());
2270
2271 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2272 }
2273
John McCall1844a6e2010-11-10 23:38:19 +00002274 /// Returns the "target" range of a canonical integral type, i.e.
2275 /// the range of values expressible in the type.
2276 ///
2277 /// This matches forValueOfCanonicalType except that enums have the
2278 /// full range of their type, not the range of their enumerators.
2279 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2280 assert(T->isCanonicalUnqualified());
2281
2282 if (const VectorType *VT = dyn_cast<VectorType>(T))
2283 T = VT->getElementType().getTypePtr();
2284 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2285 T = CT->getElementType().getTypePtr();
2286 if (const EnumType *ET = dyn_cast<EnumType>(T))
2287 T = ET->getDecl()->getIntegerType().getTypePtr();
2288
2289 const BuiltinType *BT = cast<BuiltinType>(T);
2290 assert(BT->isInteger());
2291
2292 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2293 }
2294
2295 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002296 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002297 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002298 L.NonNegative && R.NonNegative);
2299 }
2300
John McCall1844a6e2010-11-10 23:38:19 +00002301 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002302 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002303 return IntRange(std::min(L.Width, R.Width),
2304 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002305 }
2306};
2307
2308IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2309 if (value.isSigned() && value.isNegative())
2310 return IntRange(value.getMinSignedBits(), false);
2311
2312 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002313 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002314
2315 // isNonNegative() just checks the sign bit without considering
2316 // signedness.
2317 return IntRange(value.getActiveBits(), true);
2318}
2319
John McCall0acc3112010-01-06 22:57:21 +00002320IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002321 unsigned MaxWidth) {
2322 if (result.isInt())
2323 return GetValueRange(C, result.getInt(), MaxWidth);
2324
2325 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002326 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2327 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2328 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2329 R = IntRange::join(R, El);
2330 }
John McCallf2370c92010-01-06 05:24:50 +00002331 return R;
2332 }
2333
2334 if (result.isComplexInt()) {
2335 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2336 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2337 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002338 }
2339
2340 // This can happen with lossless casts to intptr_t of "based" lvalues.
2341 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002342 // FIXME: The only reason we need to pass the type in here is to get
2343 // the sign right on this one case. It would be nice if APValue
2344 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002345 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002346 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002347}
John McCallf2370c92010-01-06 05:24:50 +00002348
2349/// Pseudo-evaluate the given integer expression, estimating the
2350/// range of values it might take.
2351///
2352/// \param MaxWidth - the width to which the value will be truncated
2353IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2354 E = E->IgnoreParens();
2355
2356 // Try a full evaluation first.
2357 Expr::EvalResult result;
2358 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002359 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002360
2361 // I think we only want to look through implicit casts here; if the
2362 // user has an explicit widening cast, we should treat the value as
2363 // being of the new, wider type.
2364 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002365 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002366 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2367
John McCall1844a6e2010-11-10 23:38:19 +00002368 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002369
John McCall2de56d12010-08-25 11:45:40 +00002370 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002371
John McCallf2370c92010-01-06 05:24:50 +00002372 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002373 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002374 return OutputTypeRange;
2375
2376 IntRange SubRange
2377 = GetExprRange(C, CE->getSubExpr(),
2378 std::min(MaxWidth, OutputTypeRange.Width));
2379
2380 // Bail out if the subexpr's range is as wide as the cast type.
2381 if (SubRange.Width >= OutputTypeRange.Width)
2382 return OutputTypeRange;
2383
2384 // Otherwise, we take the smaller width, and we're non-negative if
2385 // either the output type or the subexpr is.
2386 return IntRange(SubRange.Width,
2387 SubRange.NonNegative || OutputTypeRange.NonNegative);
2388 }
2389
2390 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2391 // If we can fold the condition, just take that operand.
2392 bool CondResult;
2393 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2394 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2395 : CO->getFalseExpr(),
2396 MaxWidth);
2397
2398 // Otherwise, conservatively merge.
2399 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2400 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2401 return IntRange::join(L, R);
2402 }
2403
2404 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2405 switch (BO->getOpcode()) {
2406
2407 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002408 case BO_LAnd:
2409 case BO_LOr:
2410 case BO_LT:
2411 case BO_GT:
2412 case BO_LE:
2413 case BO_GE:
2414 case BO_EQ:
2415 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002416 return IntRange::forBoolType();
2417
John McCallc0cd21d2010-02-23 19:22:29 +00002418 // The type of these compound assignments is the type of the LHS,
2419 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002420 case BO_MulAssign:
2421 case BO_DivAssign:
2422 case BO_RemAssign:
2423 case BO_AddAssign:
2424 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002425 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002426
John McCallf2370c92010-01-06 05:24:50 +00002427 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002428 case BO_PtrMemD:
2429 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002430 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002431
John McCall60fad452010-01-06 22:07:33 +00002432 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002433 case BO_And:
2434 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002435 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2436 GetExprRange(C, BO->getRHS(), MaxWidth));
2437
John McCallf2370c92010-01-06 05:24:50 +00002438 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002439 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002440 // ...except that we want to treat '1 << (blah)' as logically
2441 // positive. It's an important idiom.
2442 if (IntegerLiteral *I
2443 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2444 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002445 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002446 return IntRange(R.Width, /*NonNegative*/ true);
2447 }
2448 }
2449 // fallthrough
2450
John McCall2de56d12010-08-25 11:45:40 +00002451 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002452 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002453
John McCall60fad452010-01-06 22:07:33 +00002454 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002455 case BO_Shr:
2456 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002457 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2458
2459 // If the shift amount is a positive constant, drop the width by
2460 // that much.
2461 llvm::APSInt shift;
2462 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2463 shift.isNonNegative()) {
2464 unsigned zext = shift.getZExtValue();
2465 if (zext >= L.Width)
2466 L.Width = (L.NonNegative ? 0 : 1);
2467 else
2468 L.Width -= zext;
2469 }
2470
2471 return L;
2472 }
2473
2474 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002475 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002476 return GetExprRange(C, BO->getRHS(), MaxWidth);
2477
John McCall60fad452010-01-06 22:07:33 +00002478 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002479 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002480 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002481 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002482 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002483
John McCallf2370c92010-01-06 05:24:50 +00002484 default:
2485 break;
2486 }
2487
2488 // Treat every other operator as if it were closed on the
2489 // narrowest type that encompasses both operands.
2490 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2491 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2492 return IntRange::join(L, R);
2493 }
2494
2495 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2496 switch (UO->getOpcode()) {
2497 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002498 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002499 return IntRange::forBoolType();
2500
2501 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002502 case UO_Deref:
2503 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002504 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002505
2506 default:
2507 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2508 }
2509 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002510
2511 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002512 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002513 }
John McCallf2370c92010-01-06 05:24:50 +00002514
2515 FieldDecl *BitField = E->getBitField();
2516 if (BitField) {
2517 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2518 unsigned BitWidth = BitWidthAP.getZExtValue();
2519
2520 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2521 }
2522
John McCall1844a6e2010-11-10 23:38:19 +00002523 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002524}
John McCall51313c32010-01-04 23:31:57 +00002525
John McCall323ed742010-05-06 08:58:33 +00002526IntRange GetExprRange(ASTContext &C, Expr *E) {
2527 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2528}
2529
John McCall51313c32010-01-04 23:31:57 +00002530/// Checks whether the given value, which currently has the given
2531/// source semantics, has the same value when coerced through the
2532/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002533bool IsSameFloatAfterCast(const llvm::APFloat &value,
2534 const llvm::fltSemantics &Src,
2535 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002536 llvm::APFloat truncated = value;
2537
2538 bool ignored;
2539 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2540 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2541
2542 return truncated.bitwiseIsEqual(value);
2543}
2544
2545/// Checks whether the given value, which currently has the given
2546/// source semantics, has the same value when coerced through the
2547/// target semantics.
2548///
2549/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002550bool IsSameFloatAfterCast(const APValue &value,
2551 const llvm::fltSemantics &Src,
2552 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002553 if (value.isFloat())
2554 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2555
2556 if (value.isVector()) {
2557 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2558 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2559 return false;
2560 return true;
2561 }
2562
2563 assert(value.isComplexFloat());
2564 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2565 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2566}
2567
John McCallb4eb64d2010-10-08 02:01:28 +00002568void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002569
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002570static bool IsZero(Sema &S, Expr *E) {
2571 // Suppress cases where we are comparing against an enum constant.
2572 if (const DeclRefExpr *DR =
2573 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2574 if (isa<EnumConstantDecl>(DR->getDecl()))
2575 return false;
2576
2577 // Suppress cases where the '0' value is expanded from a macro.
2578 if (E->getLocStart().isMacroID())
2579 return false;
2580
John McCall323ed742010-05-06 08:58:33 +00002581 llvm::APSInt Value;
2582 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2583}
2584
John McCall372e1032010-10-06 00:25:24 +00002585static bool HasEnumType(Expr *E) {
2586 // Strip off implicit integral promotions.
2587 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002588 if (ICE->getCastKind() != CK_IntegralCast &&
2589 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002590 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002591 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002592 }
2593
2594 return E->getType()->isEnumeralType();
2595}
2596
John McCall323ed742010-05-06 08:58:33 +00002597void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002598 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002599 if (E->isValueDependent())
2600 return;
2601
John McCall2de56d12010-08-25 11:45:40 +00002602 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002603 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002604 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002605 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002606 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002607 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002608 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002609 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002610 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002611 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002612 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002613 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002614 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002615 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002616 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002617 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2618 }
2619}
2620
2621/// Analyze the operands of the given comparison. Implements the
2622/// fallback case from AnalyzeComparison.
2623void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002624 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2625 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002626}
John McCall51313c32010-01-04 23:31:57 +00002627
John McCallba26e582010-01-04 23:21:16 +00002628/// \brief Implements -Wsign-compare.
2629///
2630/// \param lex the left-hand expression
2631/// \param rex the right-hand expression
2632/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002633/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002634void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2635 // The type the comparison is being performed in.
2636 QualType T = E->getLHS()->getType();
2637 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2638 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002639
John McCall323ed742010-05-06 08:58:33 +00002640 // We don't do anything special if this isn't an unsigned integral
2641 // comparison: we're only interested in integral comparisons, and
2642 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002643 //
2644 // We also don't care about value-dependent expressions or expressions
2645 // whose result is a constant.
2646 if (!T->hasUnsignedIntegerRepresentation()
2647 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002648 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002649
John McCall323ed742010-05-06 08:58:33 +00002650 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2651 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002652
John McCall323ed742010-05-06 08:58:33 +00002653 // Check to see if one of the (unmodified) operands is of different
2654 // signedness.
2655 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002656 if (lex->getType()->hasSignedIntegerRepresentation()) {
2657 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002658 "unsigned comparison between two signed integer expressions?");
2659 signedOperand = lex;
2660 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002661 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002662 signedOperand = rex;
2663 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002664 } else {
John McCall323ed742010-05-06 08:58:33 +00002665 CheckTrivialUnsignedComparison(S, E);
2666 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002667 }
2668
John McCall323ed742010-05-06 08:58:33 +00002669 // Otherwise, calculate the effective range of the signed operand.
2670 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002671
John McCall323ed742010-05-06 08:58:33 +00002672 // Go ahead and analyze implicit conversions in the operands. Note
2673 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002674 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2675 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002676
John McCall323ed742010-05-06 08:58:33 +00002677 // If the signed range is non-negative, -Wsign-compare won't fire,
2678 // but we should still check for comparisons which are always true
2679 // or false.
2680 if (signedRange.NonNegative)
2681 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002682
2683 // For (in)equality comparisons, if the unsigned operand is a
2684 // constant which cannot collide with a overflowed signed operand,
2685 // then reinterpreting the signed operand as unsigned will not
2686 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002687 if (E->isEqualityOp()) {
2688 unsigned comparisonWidth = S.Context.getIntWidth(T);
2689 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002690
John McCall323ed742010-05-06 08:58:33 +00002691 // We should never be unable to prove that the unsigned operand is
2692 // non-negative.
2693 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2694
2695 if (unsignedRange.Width < comparisonWidth)
2696 return;
2697 }
2698
2699 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2700 << lex->getType() << rex->getType()
2701 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002702}
2703
John McCall15d7d122010-11-11 03:21:53 +00002704/// Analyzes an attempt to assign the given value to a bitfield.
2705///
2706/// Returns true if there was something fishy about the attempt.
2707bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2708 SourceLocation InitLoc) {
2709 assert(Bitfield->isBitField());
2710 if (Bitfield->isInvalidDecl())
2711 return false;
2712
John McCall91b60142010-11-11 05:33:51 +00002713 // White-list bool bitfields.
2714 if (Bitfield->getType()->isBooleanType())
2715 return false;
2716
Douglas Gregor46ff3032011-02-04 13:09:01 +00002717 // Ignore value- or type-dependent expressions.
2718 if (Bitfield->getBitWidth()->isValueDependent() ||
2719 Bitfield->getBitWidth()->isTypeDependent() ||
2720 Init->isValueDependent() ||
2721 Init->isTypeDependent())
2722 return false;
2723
John McCall15d7d122010-11-11 03:21:53 +00002724 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2725
2726 llvm::APSInt Width(32);
2727 Expr::EvalResult InitValue;
2728 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002729 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002730 !InitValue.Val.isInt())
2731 return false;
2732
2733 const llvm::APSInt &Value = InitValue.Val.getInt();
2734 unsigned OriginalWidth = Value.getBitWidth();
2735 unsigned FieldWidth = Width.getZExtValue();
2736
2737 if (OriginalWidth <= FieldWidth)
2738 return false;
2739
Jay Foad9f71a8f2010-12-07 08:25:34 +00002740 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002741
2742 // It's fairly common to write values into signed bitfields
2743 // that, if sign-extended, would end up becoming a different
2744 // value. We don't want to warn about that.
2745 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002746 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002747 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002748 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002749
2750 if (Value == TruncatedValue)
2751 return false;
2752
2753 std::string PrettyValue = Value.toString(10);
2754 std::string PrettyTrunc = TruncatedValue.toString(10);
2755
2756 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2757 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2758 << Init->getSourceRange();
2759
2760 return true;
2761}
2762
John McCallbeb22aa2010-11-09 23:24:47 +00002763/// Analyze the given simple or compound assignment for warning-worthy
2764/// operations.
2765void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2766 // Just recurse on the LHS.
2767 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2768
2769 // We want to recurse on the RHS as normal unless we're assigning to
2770 // a bitfield.
2771 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002772 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2773 E->getOperatorLoc())) {
2774 // Recurse, ignoring any implicit conversions on the RHS.
2775 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2776 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002777 }
2778 }
2779
2780 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2781}
2782
John McCall51313c32010-01-04 23:31:57 +00002783/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002784void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2785 SourceLocation CContext, unsigned diag) {
2786 S.Diag(E->getExprLoc(), diag)
2787 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2788}
2789
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002790/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2791void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2792 unsigned diag) {
2793 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2794}
2795
Chandler Carruthf65076e2011-04-10 08:36:24 +00002796/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2797/// fixit hints when the cast wouldn't lose information to simply write the
2798/// expression with the expected type.
2799void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2800 SourceLocation CContext) {
2801 // Emit the primary warning first, then try to emit a fixit hint note if
2802 // reasonable.
2803 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2804 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2805
2806 const llvm::APFloat &Value = FL->getValue();
2807
2808 // Don't attempt to fix PPC double double literals.
2809 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2810 return;
2811
2812 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2813 // nice to support arbitrarily large integers here.
2814 bool isExact = false;
2815 uint64_t IntegerPart;
2816 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2817 llvm::APFloat::rmTowardZero, &isExact)
2818 != llvm::APFloat::opOK || !isExact)
2819 return;
2820
2821 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2822
2823 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2824 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2825 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2826}
2827
John McCall091f23f2010-11-09 22:22:12 +00002828std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2829 if (!Range.Width) return "0";
2830
2831 llvm::APSInt ValueInRange = Value;
2832 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002833 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002834 return ValueInRange.toString(10);
2835}
2836
Ted Kremenekef9ff882011-03-10 20:03:42 +00002837static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2838 SourceManager &smgr = S.Context.getSourceManager();
2839 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2840}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002841
John McCall323ed742010-05-06 08:58:33 +00002842void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002843 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002844 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002845
John McCall323ed742010-05-06 08:58:33 +00002846 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2847 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2848 if (Source == Target) return;
2849 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002850
Ted Kremenekef9ff882011-03-10 20:03:42 +00002851 // If the conversion context location is invalid don't complain.
2852 // We also don't want to emit a warning if the issue occurs from the
2853 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2854 // is slow, so we delay this check as long as possible. Once we detect
2855 // we are in that scenario, we just return.
2856 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002857 return;
2858
John McCall51313c32010-01-04 23:31:57 +00002859 // Never diagnose implicit casts to bool.
2860 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2861 return;
2862
2863 // Strip vector types.
2864 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002865 if (!isa<VectorType>(Target)) {
2866 if (isFromSystemMacro(S, CC))
2867 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002868 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002869 }
John McCall51313c32010-01-04 23:31:57 +00002870
2871 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2872 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2873 }
2874
2875 // Strip complex types.
2876 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002877 if (!isa<ComplexType>(Target)) {
2878 if (isFromSystemMacro(S, CC))
2879 return;
2880
John McCallb4eb64d2010-10-08 02:01:28 +00002881 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002882 }
John McCall51313c32010-01-04 23:31:57 +00002883
2884 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2885 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2886 }
2887
2888 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2889 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2890
2891 // If the source is floating point...
2892 if (SourceBT && SourceBT->isFloatingPoint()) {
2893 // ...and the target is floating point...
2894 if (TargetBT && TargetBT->isFloatingPoint()) {
2895 // ...then warn if we're dropping FP rank.
2896
2897 // Builtin FP kinds are ordered by increasing FP rank.
2898 if (SourceBT->getKind() > TargetBT->getKind()) {
2899 // Don't warn about float constants that are precisely
2900 // representable in the target type.
2901 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002902 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002903 // Value might be a float, a float vector, or a float complex.
2904 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002905 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2906 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002907 return;
2908 }
2909
Ted Kremenekef9ff882011-03-10 20:03:42 +00002910 if (isFromSystemMacro(S, CC))
2911 return;
2912
John McCallb4eb64d2010-10-08 02:01:28 +00002913 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002914 }
2915 return;
2916 }
2917
Ted Kremenekef9ff882011-03-10 20:03:42 +00002918 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002919 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002920 if (isFromSystemMacro(S, CC))
2921 return;
2922
Chandler Carrutha5b93322011-02-17 11:05:49 +00002923 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00002924 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
2925 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00002926 } else {
2927 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2928 }
2929 }
John McCall51313c32010-01-04 23:31:57 +00002930
2931 return;
2932 }
2933
John McCallf2370c92010-01-06 05:24:50 +00002934 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002935 return;
2936
John McCall323ed742010-05-06 08:58:33 +00002937 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002938 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002939
2940 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002941 // If the source is a constant, use a default-on diagnostic.
2942 // TODO: this should happen for bitfield stores, too.
2943 llvm::APSInt Value(32);
2944 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002945 if (isFromSystemMacro(S, CC))
2946 return;
2947
John McCall091f23f2010-11-09 22:22:12 +00002948 std::string PrettySourceValue = Value.toString(10);
2949 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2950
2951 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2952 << PrettySourceValue << PrettyTargetValue
2953 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2954 return;
2955 }
2956
John McCall51313c32010-01-04 23:31:57 +00002957 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2958 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002959
2960 if (isFromSystemMacro(S, CC))
2961 return;
2962
John McCallf2370c92010-01-06 05:24:50 +00002963 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002964 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2965 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002966 }
2967
2968 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2969 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2970 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002971
2972 if (isFromSystemMacro(S, CC))
2973 return;
2974
John McCall323ed742010-05-06 08:58:33 +00002975 unsigned DiagID = diag::warn_impcast_integer_sign;
2976
2977 // Traditionally, gcc has warned about this under -Wsign-compare.
2978 // We also want to warn about it in -Wconversion.
2979 // So if -Wconversion is off, use a completely identical diagnostic
2980 // in the sign-compare group.
2981 // The conditional-checking code will
2982 if (ICContext) {
2983 DiagID = diag::warn_impcast_integer_sign_conditional;
2984 *ICContext = true;
2985 }
2986
John McCallb4eb64d2010-10-08 02:01:28 +00002987 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002988 }
2989
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002990 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002991 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2992 // type, to give us better diagnostics.
2993 QualType SourceType = E->getType();
2994 if (!S.getLangOptions().CPlusPlus) {
2995 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2996 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2997 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2998 SourceType = S.Context.getTypeDeclType(Enum);
2999 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3000 }
3001 }
3002
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003003 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3004 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3005 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003006 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003007 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003008 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003009 SourceEnum != TargetEnum) {
3010 if (isFromSystemMacro(S, CC))
3011 return;
3012
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003013 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003014 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003015 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003016
John McCall51313c32010-01-04 23:31:57 +00003017 return;
3018}
3019
John McCall323ed742010-05-06 08:58:33 +00003020void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3021
3022void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003023 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003024 E = E->IgnoreParenImpCasts();
3025
3026 if (isa<ConditionalOperator>(E))
3027 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3028
John McCallb4eb64d2010-10-08 02:01:28 +00003029 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003030 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003031 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003032 return;
3033}
3034
3035void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003036 SourceLocation CC = E->getQuestionLoc();
3037
3038 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003039
3040 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003041 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3042 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003043
3044 // If -Wconversion would have warned about either of the candidates
3045 // for a signedness conversion to the context type...
3046 if (!Suspicious) return;
3047
3048 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003049 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3050 CC))
John McCall323ed742010-05-06 08:58:33 +00003051 return;
3052
3053 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003054 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003055 return;
3056
3057 // ...then check whether it would have warned about either of the
3058 // candidates for a signedness conversion to the condition type.
3059 if (E->getType() != T) {
3060 Suspicious = false;
3061 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003062 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003063 if (!Suspicious)
3064 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003065 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003066 if (!Suspicious)
3067 return;
3068 }
3069
3070 // If so, emit a diagnostic under -Wsign-compare.
3071 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3072 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3073 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3074 << lex->getType() << rex->getType()
3075 << lex->getSourceRange() << rex->getSourceRange();
3076}
3077
3078/// AnalyzeImplicitConversions - Find and report any interesting
3079/// implicit conversions in the given expression. There are a couple
3080/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003081void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003082 QualType T = OrigE->getType();
3083 Expr *E = OrigE->IgnoreParenImpCasts();
3084
3085 // For conditional operators, we analyze the arguments as if they
3086 // were being fed directly into the output.
3087 if (isa<ConditionalOperator>(E)) {
3088 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3089 CheckConditionalOperator(S, CO, T);
3090 return;
3091 }
3092
3093 // Go ahead and check any implicit conversions we might have skipped.
3094 // The non-canonical typecheck is just an optimization;
3095 // CheckImplicitConversion will filter out dead implicit conversions.
3096 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003097 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003098
3099 // Now continue drilling into this expression.
3100
3101 // Skip past explicit casts.
3102 if (isa<ExplicitCastExpr>(E)) {
3103 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003104 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003105 }
3106
John McCallbeb22aa2010-11-09 23:24:47 +00003107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3108 // Do a somewhat different check with comparison operators.
3109 if (BO->isComparisonOp())
3110 return AnalyzeComparison(S, BO);
3111
3112 // And with assignments and compound assignments.
3113 if (BO->isAssignmentOp())
3114 return AnalyzeAssignment(S, BO);
3115 }
John McCall323ed742010-05-06 08:58:33 +00003116
3117 // These break the otherwise-useful invariant below. Fortunately,
3118 // we don't really need to recurse into them, because any internal
3119 // expressions should have been analyzed already when they were
3120 // built into statements.
3121 if (isa<StmtExpr>(E)) return;
3122
3123 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003124 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003125
3126 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003127 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003128 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003129 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003130}
3131
3132} // end anonymous namespace
3133
3134/// Diagnoses "dangerous" implicit conversions within the given
3135/// expression (which is a full expression). Implements -Wconversion
3136/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003137///
3138/// \param CC the "context" location of the implicit conversion, i.e.
3139/// the most location of the syntactic entity requiring the implicit
3140/// conversion
3141void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003142 // Don't diagnose in unevaluated contexts.
3143 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3144 return;
3145
3146 // Don't diagnose for value- or type-dependent expressions.
3147 if (E->isTypeDependent() || E->isValueDependent())
3148 return;
3149
John McCallb4eb64d2010-10-08 02:01:28 +00003150 // This is not the right CC for (e.g.) a variable initialization.
3151 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003152}
3153
John McCall15d7d122010-11-11 03:21:53 +00003154void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3155 FieldDecl *BitField,
3156 Expr *Init) {
3157 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3158}
3159
Mike Stumpf8c49212010-01-21 03:59:47 +00003160/// CheckParmsForFunctionDef - Check that the parameters of the given
3161/// function are appropriate for the definition of a function. This
3162/// takes care of any checks that cannot be performed on the
3163/// declaration itself, e.g., that the types of each of the function
3164/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003165bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3166 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003167 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003168 for (; P != PEnd; ++P) {
3169 ParmVarDecl *Param = *P;
3170
Mike Stumpf8c49212010-01-21 03:59:47 +00003171 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3172 // function declarator that is part of a function definition of
3173 // that function shall not have incomplete type.
3174 //
3175 // This is also C++ [dcl.fct]p6.
3176 if (!Param->isInvalidDecl() &&
3177 RequireCompleteType(Param->getLocation(), Param->getType(),
3178 diag::err_typecheck_decl_incomplete_type)) {
3179 Param->setInvalidDecl();
3180 HasInvalidParm = true;
3181 }
3182
3183 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3184 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003185 if (CheckParameterNames &&
3186 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003187 !Param->isImplicit() &&
3188 !getLangOptions().CPlusPlus)
3189 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003190
3191 // C99 6.7.5.3p12:
3192 // If the function declarator is not part of a definition of that
3193 // function, parameters may have incomplete type and may use the [*]
3194 // notation in their sequences of declarator specifiers to specify
3195 // variable length array types.
3196 QualType PType = Param->getOriginalType();
3197 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3198 if (AT->getSizeModifier() == ArrayType::Star) {
3199 // FIXME: This diagnosic should point the the '[*]' if source-location
3200 // information is added for it.
3201 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3202 }
3203 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003204 }
3205
3206 return HasInvalidParm;
3207}
John McCallb7f4ffe2010-08-12 21:44:57 +00003208
3209/// CheckCastAlign - Implements -Wcast-align, which warns when a
3210/// pointer cast increases the alignment requirements.
3211void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3212 // This is actually a lot of work to potentially be doing on every
3213 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003214 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3215 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003216 == Diagnostic::Ignored)
3217 return;
3218
3219 // Ignore dependent types.
3220 if (T->isDependentType() || Op->getType()->isDependentType())
3221 return;
3222
3223 // Require that the destination be a pointer type.
3224 const PointerType *DestPtr = T->getAs<PointerType>();
3225 if (!DestPtr) return;
3226
3227 // If the destination has alignment 1, we're done.
3228 QualType DestPointee = DestPtr->getPointeeType();
3229 if (DestPointee->isIncompleteType()) return;
3230 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3231 if (DestAlign.isOne()) return;
3232
3233 // Require that the source be a pointer type.
3234 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3235 if (!SrcPtr) return;
3236 QualType SrcPointee = SrcPtr->getPointeeType();
3237
3238 // Whitelist casts from cv void*. We already implicitly
3239 // whitelisted casts to cv void*, since they have alignment 1.
3240 // Also whitelist casts involving incomplete types, which implicitly
3241 // includes 'void'.
3242 if (SrcPointee->isIncompleteType()) return;
3243
3244 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3245 if (SrcAlign >= DestAlign) return;
3246
3247 Diag(TRange.getBegin(), diag::warn_cast_align)
3248 << Op->getType() << T
3249 << static_cast<unsigned>(SrcAlign.getQuantity())
3250 << static_cast<unsigned>(DestAlign.getQuantity())
3251 << TRange << Op->getSourceRange();
3252}
3253
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003254static void CheckArrayAccess_Check(Sema &S,
3255 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003256 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003257 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003258 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003259 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003260 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003261
Chandler Carruth34064582011-02-17 20:55:08 +00003262 const Expr *IndexExpr = E->getIdx();
3263 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003264 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003265 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003266 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003267 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003268
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003269 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003270 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003271 if (!size.isStrictlyPositive())
3272 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003273 if (size.getBitWidth() > index.getBitWidth())
3274 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003275 else if (size.getBitWidth() < index.getBitWidth())
3276 size = size.sext(index.getBitWidth());
3277
Chandler Carruth34064582011-02-17 20:55:08 +00003278 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003279 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003280
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003281 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3282 S.PDiag(diag::warn_array_index_exceeds_bounds)
3283 << index.toString(10, true)
3284 << size.toString(10, true)
3285 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003286 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003287 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3288 S.PDiag(diag::warn_array_index_precedes_bounds)
3289 << index.toString(10, true)
3290 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003291 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003292
3293 const NamedDecl *ND = NULL;
3294 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3295 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3296 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3297 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3298 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003299 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3300 S.PDiag(diag::note_array_index_out_of_bounds)
3301 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003302}
3303
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003304void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003305 while (true) {
3306 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003307 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003308 case Stmt::ArraySubscriptExprClass:
3309 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3310 return;
3311 case Stmt::ConditionalOperatorClass: {
3312 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3313 if (const Expr *lhs = cond->getLHS())
3314 CheckArrayAccess(lhs);
3315 if (const Expr *rhs = cond->getRHS())
3316 CheckArrayAccess(rhs);
3317 return;
3318 }
3319 default:
3320 return;
3321 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003322 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003323}