blob: 530f81289a9a70666475cfde2d57b3bdc34d2426 [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"
John McCallf85e1932011-06-15 23:02:42 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000026#include "clang/AST/DeclObjC.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000029#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000032#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000033#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000034#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000035#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000036#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000037using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000038using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000039
Chris Lattner60800082009-02-18 17:49:48 +000040SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
41 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000042 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
43 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000044}
Chris Lattner08f92e32010-11-17 07:37:15 +000045
Chris Lattner60800082009-02-18 17:49:48 +000046
Ryan Flynn4403a5e2009-08-06 03:00:50 +000047/// CheckablePrintfAttr - does a function call have a "printf" attribute
48/// and arguments that merit checking?
49bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
50 if (Format->getType() == "printf") return true;
51 if (Format->getType() == "printf0") {
52 // printf0 allows null "format" string; if so don't check format/args
53 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000054 // Does the index refer to the implicit object argument?
55 if (isa<CXXMemberCallExpr>(TheCall)) {
56 if (format_idx == 0)
57 return false;
58 --format_idx;
59 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000060 if (format_idx < TheCall->getNumArgs()) {
61 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000062 if (!Format->isNullPointerConstant(Context,
63 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000064 return true;
65 }
66 }
67 return false;
68}
Chris Lattner60800082009-02-18 17:49:48 +000069
John McCall8e10f3b2011-02-26 05:39:39 +000070/// Checks that a call expression's argument count is the desired number.
71/// This is useful when doing custom type-checking. Returns true on error.
72static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
73 unsigned argCount = call->getNumArgs();
74 if (argCount == desiredArgCount) return false;
75
76 if (argCount < desiredArgCount)
77 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
78 << 0 /*function call*/ << desiredArgCount << argCount
79 << call->getSourceRange();
80
81 // Highlight all the excess arguments.
82 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
83 call->getArg(argCount - 1)->getLocEnd());
84
85 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
86 << 0 /*function call*/ << desiredArgCount << argCount
87 << call->getArg(1)->getSourceRange();
88}
89
John McCall60d7b3a2010-08-24 06:29:42 +000090ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000091Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000092 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000093
Chris Lattner946928f2010-10-01 23:23:24 +000094 // Find out if any arguments are required to be integer constant expressions.
95 unsigned ICEArguments = 0;
96 ASTContext::GetBuiltinTypeError Error;
97 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
98 if (Error != ASTContext::GE_None)
99 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
100
101 // If any arguments are required to be ICE's, check and diagnose.
102 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
103 // Skip arguments not required to be ICE's.
104 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
105
106 llvm::APSInt Result;
107 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
108 return true;
109 ICEArguments &= ~(1 << ArgNo);
110 }
111
Anders Carlssond406bf02009-08-16 01:56:34 +0000112 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000113 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000114 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000115 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000116 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000117 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000118 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000119 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000120 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121 if (SemaBuiltinVAStart(TheCall))
122 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000123 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 case Builtin::BI__builtin_isgreater:
125 case Builtin::BI__builtin_isgreaterequal:
126 case Builtin::BI__builtin_isless:
127 case Builtin::BI__builtin_islessequal:
128 case Builtin::BI__builtin_islessgreater:
129 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinUnorderedCompare(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000133 case Builtin::BI__builtin_fpclassify:
134 if (SemaBuiltinFPClassification(TheCall, 6))
135 return ExprError();
136 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000137 case Builtin::BI__builtin_isfinite:
138 case Builtin::BI__builtin_isinf:
139 case Builtin::BI__builtin_isinf_sign:
140 case Builtin::BI__builtin_isnan:
141 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000142 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000143 return ExprError();
144 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000145 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 return SemaBuiltinShuffleVector(TheCall);
147 // TheCall will be freed by the smart pointer here, but that's fine, since
148 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000149 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000150 if (SemaBuiltinPrefetch(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000153 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinObjectSize(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000157 case Builtin::BI__builtin_longjmp:
158 if (SemaBuiltinLongjmp(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000161
162 case Builtin::BI__builtin_classify_type:
163 if (checkArgCount(*this, TheCall, 1)) return true;
164 TheCall->setType(Context.IntTy);
165 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000166 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000167 if (checkArgCount(*this, TheCall, 1)) return true;
168 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000169 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000170 case Builtin::BI__sync_fetch_and_add:
171 case Builtin::BI__sync_fetch_and_sub:
172 case Builtin::BI__sync_fetch_and_or:
173 case Builtin::BI__sync_fetch_and_and:
174 case Builtin::BI__sync_fetch_and_xor:
175 case Builtin::BI__sync_add_and_fetch:
176 case Builtin::BI__sync_sub_and_fetch:
177 case Builtin::BI__sync_and_and_fetch:
178 case Builtin::BI__sync_or_and_fetch:
179 case Builtin::BI__sync_xor_and_fetch:
180 case Builtin::BI__sync_val_compare_and_swap:
181 case Builtin::BI__sync_bool_compare_and_swap:
182 case Builtin::BI__sync_lock_test_and_set:
183 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000184 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000185 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000186 }
187
188 // Since the target specific builtins for each arch overlap, only check those
189 // of the arch we are compiling for.
190 if (BuiltinID >= Builtin::FirstTSBuiltin) {
191 switch (Context.Target.getTriple().getArch()) {
192 case llvm::Triple::arm:
193 case llvm::Triple::thumb:
194 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
195 return ExprError();
196 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000197 default:
198 break;
199 }
200 }
201
202 return move(TheCallResult);
203}
204
Nate Begeman61eecf52010-06-14 05:21:25 +0000205// Get the valid immediate range for the specified NEON type code.
206static unsigned RFT(unsigned t, bool shift = false) {
207 bool quad = t & 0x10;
208
209 switch (t & 0x7) {
210 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000211 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000212 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000213 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000214 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000215 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000216 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000217 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000218 case 4: // f32
219 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000220 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000221 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000222 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000223 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000224 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000225 case 7: // float16
226 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000227 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000228 }
229 return 0;
230}
231
Nate Begeman26a31422010-06-08 02:47:44 +0000232bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000233 llvm::APSInt Result;
234
Nate Begeman0d15c532010-06-13 04:47:52 +0000235 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000236 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000237 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000238#define GET_NEON_OVERLOAD_CHECK
239#include "clang/Basic/arm_neon.inc"
240#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000241 }
242
Nate Begeman0d15c532010-06-13 04:47:52 +0000243 // For NEON intrinsics which are overloaded on vector element type, validate
244 // the immediate which specifies which variant to emit.
245 if (mask) {
246 unsigned ArgNo = TheCall->getNumArgs()-1;
247 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
248 return true;
249
Nate Begeman61eecf52010-06-14 05:21:25 +0000250 TV = Result.getLimitedValue(32);
251 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000252 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
253 << TheCall->getArg(ArgNo)->getSourceRange();
254 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000255
Nate Begeman0d15c532010-06-13 04:47:52 +0000256 // For NEON intrinsics which take an immediate value as part of the
257 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000258 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000259 switch (BuiltinID) {
260 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000261 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
262 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000263 case ARM::BI__builtin_arm_vcvtr_f:
264 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000265#define GET_NEON_IMMEDIATE_CHECK
266#include "clang/Basic/arm_neon.inc"
267#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000268 };
269
Nate Begeman61eecf52010-06-14 05:21:25 +0000270 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000271 if (SemaBuiltinConstantArg(TheCall, i, Result))
272 return true;
273
Nate Begeman61eecf52010-06-14 05:21:25 +0000274 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000275 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000276 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000277 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000278 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000279
Nate Begeman99c40bb2010-08-03 21:32:34 +0000280 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000281 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000282}
Daniel Dunbarde454282008-10-02 18:44:07 +0000283
Anders Carlssond406bf02009-08-16 01:56:34 +0000284/// CheckFunctionCall - Check a direct function call for various correctness
285/// and safety properties not strictly enforced by the C type system.
286bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
287 // Get the IdentifierInfo* for the called function.
288 IdentifierInfo *FnInfo = FDecl->getIdentifier();
289
290 // None of the checks below are needed for functions that don't have
291 // simple names (e.g., C++ conversion functions).
292 if (!FnInfo)
293 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Daniel Dunbarde454282008-10-02 18:44:07 +0000295 // FIXME: This mechanism should be abstracted to be less fragile and
296 // more efficient. For example, just map function ids to custom
297 // handlers.
298
Ted Kremenekc82faca2010-09-09 04:33:05 +0000299 // Printf and scanf checking.
300 for (specific_attr_iterator<FormatAttr>
301 i = FDecl->specific_attr_begin<FormatAttr>(),
302 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
303
304 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000305 const bool b = Format->getType() == "scanf";
306 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000307 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000308 CheckPrintfScanfArguments(TheCall, HasVAListArg,
309 Format->getFormatIdx() - 1,
310 HasVAListArg ? 0 : Format->getFirstArg() - 1,
311 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000312 }
Chris Lattner59907c42007-08-10 20:18:51 +0000313 }
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Ted Kremenekc82faca2010-09-09 04:33:05 +0000315 for (specific_attr_iterator<NonNullAttr>
316 i = FDecl->specific_attr_begin<NonNullAttr>(),
317 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000318 CheckNonNullArguments(*i, TheCall->getArgs(),
319 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000320 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000321
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000322 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000323 int CMF = -1;
324 switch (FDecl->getBuiltinID()) {
325 case Builtin::BI__builtin_memset:
326 case Builtin::BI__builtin___memset_chk:
327 case Builtin::BImemset:
328 CMF = CMF_Memset;
329 break;
330
331 case Builtin::BI__builtin_memcpy:
332 case Builtin::BI__builtin___memcpy_chk:
333 case Builtin::BImemcpy:
334 CMF = CMF_Memcpy;
335 break;
336
337 case Builtin::BI__builtin_memmove:
338 case Builtin::BI__builtin___memmove_chk:
339 case Builtin::BImemmove:
340 CMF = CMF_Memmove;
341 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000342
343 case Builtin::BIstrlcpy:
344 case Builtin::BIstrlcat:
345 CheckStrlcpycatArguments(TheCall, FnInfo);
346 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000347
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000348 case Builtin::BI__builtin_memcmp:
349 CMF = CMF_Memcmp;
350 break;
351
Douglas Gregor707a23e2011-06-16 17:56:04 +0000352 default:
353 if (FDecl->getLinkage() == ExternalLinkage &&
354 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
355 if (FnInfo->isStr("memset"))
356 CMF = CMF_Memset;
357 else if (FnInfo->isStr("memcpy"))
358 CMF = CMF_Memcpy;
359 else if (FnInfo->isStr("memmove"))
360 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000361 else if (FnInfo->isStr("memcmp"))
362 CMF = CMF_Memcmp;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000363 }
364 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000365 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000366
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000367 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000368 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000369 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000370
Anders Carlssond406bf02009-08-16 01:56:34 +0000371 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000372}
373
Anders Carlssond406bf02009-08-16 01:56:34 +0000374bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000375 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000376 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000377 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000378 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000380 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
381 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000384 QualType Ty = V->getType();
385 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek826a3452010-07-16 02:11:22 +0000388 const bool b = Format->getType() == "scanf";
389 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000390 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Anders Carlssond406bf02009-08-16 01:56:34 +0000392 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000393 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
394 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000395
396 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000397}
398
Chris Lattner5caa3702009-05-08 06:58:22 +0000399/// SemaBuiltinAtomicOverloaded - We have a call to a function like
400/// __sync_fetch_and_add, which is an overloaded function based on the pointer
401/// type of its first argument. The main ActOnCallExpr routines have already
402/// promoted the types of arguments because all of these calls are prototyped as
403/// void(...).
404///
405/// This function goes through and does final semantic checking for these
406/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000407ExprResult
408Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000409 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000410 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
411 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
412
413 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000414 if (TheCall->getNumArgs() < 1) {
415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
416 << 0 << 1 << TheCall->getNumArgs()
417 << TheCall->getCallee()->getSourceRange();
418 return ExprError();
419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 // Inspect the first argument of the atomic builtin. This should always be
422 // a pointer type, whose element is an integral scalar or pointer type.
423 // Because it is a pointer type, we don't have to worry about any implicit
424 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000425 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000426 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000427 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
428 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000429 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
430 << FirstArg->getType() << FirstArg->getSourceRange();
431 return ExprError();
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
John McCallf85e1932011-06-15 23:02:42 +0000434 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000435 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000436 !ValType->isBlockPointerType()) {
437 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
438 << FirstArg->getType() << FirstArg->getSourceRange();
439 return ExprError();
440 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000441
John McCallf85e1932011-06-15 23:02:42 +0000442 switch (ValType.getObjCLifetime()) {
443 case Qualifiers::OCL_None:
444 case Qualifiers::OCL_ExplicitNone:
445 // okay
446 break;
447
448 case Qualifiers::OCL_Weak:
449 case Qualifiers::OCL_Strong:
450 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000451 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000452 << ValType << FirstArg->getSourceRange();
453 return ExprError();
454 }
455
Chandler Carruth8d13d222010-07-18 20:54:12 +0000456 // The majority of builtins return a value, but a few have special return
457 // types, so allow them to override appropriately below.
458 QualType ResultType = ValType;
459
Chris Lattner5caa3702009-05-08 06:58:22 +0000460 // We need to figure out which concrete builtin this maps onto. For example,
461 // __sync_fetch_and_add with a 2 byte object turns into
462 // __sync_fetch_and_add_2.
463#define BUILTIN_ROW(x) \
464 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
465 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Chris Lattner5caa3702009-05-08 06:58:22 +0000467 static const unsigned BuiltinIndices[][5] = {
468 BUILTIN_ROW(__sync_fetch_and_add),
469 BUILTIN_ROW(__sync_fetch_and_sub),
470 BUILTIN_ROW(__sync_fetch_and_or),
471 BUILTIN_ROW(__sync_fetch_and_and),
472 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 BUILTIN_ROW(__sync_add_and_fetch),
475 BUILTIN_ROW(__sync_sub_and_fetch),
476 BUILTIN_ROW(__sync_and_and_fetch),
477 BUILTIN_ROW(__sync_or_and_fetch),
478 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner5caa3702009-05-08 06:58:22 +0000480 BUILTIN_ROW(__sync_val_compare_and_swap),
481 BUILTIN_ROW(__sync_bool_compare_and_swap),
482 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000483 BUILTIN_ROW(__sync_lock_release),
484 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000485 };
Mike Stump1eb44332009-09-09 15:08:12 +0000486#undef BUILTIN_ROW
487
Chris Lattner5caa3702009-05-08 06:58:22 +0000488 // Determine the index of the size.
489 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000490 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000491 case 1: SizeIndex = 0; break;
492 case 2: SizeIndex = 1; break;
493 case 4: SizeIndex = 2; break;
494 case 8: SizeIndex = 3; break;
495 case 16: SizeIndex = 4; break;
496 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000497 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
498 << FirstArg->getType() << FirstArg->getSourceRange();
499 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Chris Lattner5caa3702009-05-08 06:58:22 +0000502 // Each of these builtins has one pointer argument, followed by some number of
503 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
504 // that we ignore. Find out which row of BuiltinIndices to read from as well
505 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000506 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000507 unsigned BuiltinIndex, NumFixed = 1;
508 switch (BuiltinID) {
509 default: assert(0 && "Unknown overloaded atomic builtin!");
510 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
511 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
512 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
513 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
514 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000516 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
517 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
518 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
519 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
520 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner5caa3702009-05-08 06:58:22 +0000522 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000523 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000524 NumFixed = 2;
525 break;
526 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000527 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000528 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000529 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000530 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000531 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000532 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000533 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000534 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000535 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000536 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000537 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Chris Lattner5caa3702009-05-08 06:58:22 +0000540 // Now that we know how many fixed arguments we expect, first check that we
541 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000542 if (TheCall->getNumArgs() < 1+NumFixed) {
543 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
544 << 0 << 1+NumFixed << TheCall->getNumArgs()
545 << TheCall->getCallee()->getSourceRange();
546 return ExprError();
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000549 // Get the decl for the concrete builtin from this, we can tell what the
550 // concrete integer type we should convert to is.
551 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
552 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
553 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000554 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000555 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
556 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000557
John McCallf871d0c2010-08-07 06:22:56 +0000558 // The first argument --- the pointer --- has a fixed type; we
559 // deduce the types of the rest of the arguments accordingly. Walk
560 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000561 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000562 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner5caa3702009-05-08 06:58:22 +0000564 // If the argument is an implicit cast, then there was a promotion due to
565 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000566 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000567 Arg = ICE->getSubExpr();
568 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000569 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000570 }
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Chris Lattner5caa3702009-05-08 06:58:22 +0000572 // GCC does an implicit conversion to the pointer or integer ValType. This
573 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000574 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000575 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000576 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000577 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
578 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000579 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000580 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattner5caa3702009-05-08 06:58:22 +0000582 // Okay, we have something that *can* be converted to the right type. Check
583 // to see if there is a potentially weird extension going on here. This can
584 // happen when you do an atomic operation on something like an char* and
585 // pass in 42. The 42 gets converted to char. This is even more strange
586 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000587 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000588 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
589 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000590 }
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner5caa3702009-05-08 06:58:22 +0000592 // Switch the DeclRefExpr to refer to the new decl.
593 DRE->setDecl(NewBuiltinDecl);
594 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner5caa3702009-05-08 06:58:22 +0000596 // Set the callee in the CallExpr.
597 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000598 ExprResult PromotedCall = UsualUnaryConversions(DRE);
599 if (PromotedCall.isInvalid())
600 return ExprError();
601 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000603 // Change the result type of the call to match the original value type. This
604 // is arbitrary, but the codegen for these builtins ins design to handle it
605 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000606 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000607
608 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000609}
610
611
Chris Lattner69039812009-02-18 06:01:06 +0000612/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000613/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000614/// Note: It might also make sense to do the UTF-16 conversion here (would
615/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000616bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000617 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000618 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
619
Douglas Gregor5cee1192011-07-27 05:40:30 +0000620 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000621 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
622 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000623 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000626 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000627 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000628 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000629 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000630 const UTF8 *FromPtr = (UTF8 *)String.data();
631 UTF16 *ToPtr = &ToBuf[0];
632
633 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
634 &ToPtr, ToPtr + NumBytes,
635 strictConversion);
636 // Check for conversion failure.
637 if (Result != conversionOK)
638 Diag(Arg->getLocStart(),
639 diag::warn_cfstring_truncated) << Arg->getSourceRange();
640 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000641 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000642}
643
Chris Lattnerc27c6652007-12-20 00:05:45 +0000644/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
645/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000646bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
647 Expr *Fn = TheCall->getCallee();
648 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000649 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000650 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000651 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
652 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000653 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000655 return true;
656 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000657
658 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000659 return Diag(TheCall->getLocEnd(),
660 diag::err_typecheck_call_too_few_args_at_least)
661 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000662 }
663
Chris Lattnerc27c6652007-12-20 00:05:45 +0000664 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000665 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000666 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000667 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000668 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000669 else if (FunctionDecl *FD = getCurFunctionDecl())
670 isVariadic = FD->isVariadic();
671 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000672 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattnerc27c6652007-12-20 00:05:45 +0000674 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000675 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
676 return true;
677 }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner30ce3442007-12-19 23:59:04 +0000679 // Verify that the second argument to the builtin is the last argument of the
680 // current function or method.
681 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000682 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Anders Carlsson88cf2262008-02-11 04:20:54 +0000684 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
685 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000686 // FIXME: This isn't correct for methods (results in bogus warning).
687 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000688 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000689 if (CurBlock)
690 LastArg = *(CurBlock->TheDecl->param_end()-1);
691 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000692 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000693 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000694 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000695 SecondArgIsLastNamedArgument = PV == LastArg;
696 }
697 }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattner30ce3442007-12-19 23:59:04 +0000699 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000700 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000701 diag::warn_second_parameter_of_va_start_not_last_named_argument);
702 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000703}
Chris Lattner30ce3442007-12-19 23:59:04 +0000704
Chris Lattner1b9a0792007-12-20 00:26:33 +0000705/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
706/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000707bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
708 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000709 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000710 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000711 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000712 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000713 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000714 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000715 << SourceRange(TheCall->getArg(2)->getLocStart(),
716 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000717
John Wiegley429bb272011-04-08 18:41:53 +0000718 ExprResult OrigArg0 = TheCall->getArg(0);
719 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000720
Chris Lattner1b9a0792007-12-20 00:26:33 +0000721 // Do standard promotions between the two arguments, returning their common
722 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000723 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000724 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
725 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000726
727 // Make sure any conversions are pushed back into the call; this is
728 // type safe since unordered compare builtins are declared as "_Bool
729 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000730 TheCall->setArg(0, OrigArg0.get());
731 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000732
John Wiegley429bb272011-04-08 18:41:53 +0000733 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000734 return false;
735
Chris Lattner1b9a0792007-12-20 00:26:33 +0000736 // If the common type isn't a real floating type, then the arguments were
737 // invalid for this operation.
738 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000739 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000740 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000741 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
742 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattner1b9a0792007-12-20 00:26:33 +0000744 return false;
745}
746
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000747/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
748/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000749/// to check everything. We expect the last argument to be a floating point
750/// value.
751bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
752 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000753 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000754 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000755 if (TheCall->getNumArgs() > NumArgs)
756 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000757 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000758 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000759 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000760 (*(TheCall->arg_end()-1))->getLocEnd());
761
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000762 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Eli Friedman9ac6f622009-08-31 20:06:00 +0000764 if (OrigArg->isTypeDependent())
765 return false;
766
Chris Lattner81368fb2010-05-06 05:50:07 +0000767 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000768 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000769 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000770 diag::err_typecheck_call_invalid_unary_fp)
771 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner81368fb2010-05-06 05:50:07 +0000773 // If this is an implicit conversion from float -> double, remove it.
774 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
775 Expr *CastArg = Cast->getSubExpr();
776 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
777 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
778 "promotion from float to double is the only expected cast here");
779 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000780 TheCall->setArg(NumArgs-1, CastArg);
781 OrigArg = CastArg;
782 }
783 }
784
Eli Friedman9ac6f622009-08-31 20:06:00 +0000785 return false;
786}
787
Eli Friedmand38617c2008-05-14 19:38:39 +0000788/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
789// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000790ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000791 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000792 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000793 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000794 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000795 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000796
Nate Begeman37b6a572010-06-08 00:16:34 +0000797 // Determine which of the following types of shufflevector we're checking:
798 // 1) unary, vector mask: (lhs, mask)
799 // 2) binary, vector mask: (lhs, rhs, mask)
800 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
801 QualType resType = TheCall->getArg(0)->getType();
802 unsigned numElements = 0;
803
Douglas Gregorcde01732009-05-19 22:10:17 +0000804 if (!TheCall->getArg(0)->isTypeDependent() &&
805 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000806 QualType LHSType = TheCall->getArg(0)->getType();
807 QualType RHSType = TheCall->getArg(1)->getType();
808
809 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000810 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000811 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000812 TheCall->getArg(1)->getLocEnd());
813 return ExprError();
814 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000815
816 numElements = LHSType->getAs<VectorType>()->getNumElements();
817 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Nate Begeman37b6a572010-06-08 00:16:34 +0000819 // Check to see if we have a call with 2 vector arguments, the unary shuffle
820 // with mask. If so, verify that RHS is an integer vector type with the
821 // same number of elts as lhs.
822 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000823 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000824 RHSType->getAs<VectorType>()->getNumElements() != numElements)
825 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
826 << SourceRange(TheCall->getArg(1)->getLocStart(),
827 TheCall->getArg(1)->getLocEnd());
828 numResElements = numElements;
829 }
830 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000831 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000832 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000833 TheCall->getArg(1)->getLocEnd());
834 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000835 } else if (numElements != numResElements) {
836 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000837 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000838 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000839 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000840 }
841
842 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000843 if (TheCall->getArg(i)->isTypeDependent() ||
844 TheCall->getArg(i)->isValueDependent())
845 continue;
846
Nate Begeman37b6a572010-06-08 00:16:34 +0000847 llvm::APSInt Result(32);
848 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
849 return ExprError(Diag(TheCall->getLocStart(),
850 diag::err_shufflevector_nonconstant_argument)
851 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000852
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000853 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000854 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000855 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000856 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000857 }
858
Chris Lattner5f9e2722011-07-23 10:55:15 +0000859 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +0000860
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000861 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000862 exprs.push_back(TheCall->getArg(i));
863 TheCall->setArg(i, 0);
864 }
865
Nate Begemana88dc302009-08-12 02:10:25 +0000866 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000867 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000868 TheCall->getCallee()->getLocStart(),
869 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000870}
Chris Lattner30ce3442007-12-19 23:59:04 +0000871
Daniel Dunbar4493f792008-07-21 22:59:13 +0000872/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
873// This is declared to take (const void*, ...) and can take two
874// optional constant int args.
875bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000876 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000877
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000878 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000879 return Diag(TheCall->getLocEnd(),
880 diag::err_typecheck_call_too_many_args_at_most)
881 << 0 /*function call*/ << 3 << NumArgs
882 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000883
884 // Argument 0 is checked for us and the remaining arguments must be
885 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000886 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000887 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000888
Eli Friedman9aef7262009-12-04 00:30:06 +0000889 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000890 if (SemaBuiltinConstantArg(TheCall, i, Result))
891 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Daniel Dunbar4493f792008-07-21 22:59:13 +0000893 // FIXME: gcc issues a warning and rewrites these to 0. These
894 // seems especially odd for the third argument since the default
895 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000896 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000897 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000898 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000899 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000900 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000901 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000902 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000903 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000904 }
905 }
906
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000907 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000908}
909
Eric Christopher691ebc32010-04-17 02:26:23 +0000910/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
911/// TheCall is a constant expression.
912bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
913 llvm::APSInt &Result) {
914 Expr *Arg = TheCall->getArg(ArgNum);
915 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
916 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
917
918 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
919
920 if (!Arg->isIntegerConstantExpr(Result, Context))
921 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000922 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000923
Chris Lattner21fb98e2009-09-23 06:06:36 +0000924 return false;
925}
926
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000927/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
928/// int type). This simply type checks that type is one of the defined
929/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000930// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000931bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000932 llvm::APSInt Result;
933
934 // Check constant-ness first.
935 if (SemaBuiltinConstantArg(TheCall, 1, Result))
936 return true;
937
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000938 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000939 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000940 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
941 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000942 }
943
944 return false;
945}
946
Eli Friedman586d6a82009-05-03 06:04:26 +0000947/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000948/// This checks that val is a constant 1.
949bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
950 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000951 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000952
Eric Christopher691ebc32010-04-17 02:26:23 +0000953 // TODO: This is less than ideal. Overload this to take a value.
954 if (SemaBuiltinConstantArg(TheCall, 1, Result))
955 return true;
956
957 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000958 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
959 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
960
961 return false;
962}
963
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000964// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000965bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
966 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000967 unsigned format_idx, unsigned firstDataArg,
968 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000969 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000970 if (E->isTypeDependent() || E->isValueDependent())
971 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000972
Peter Collingbournef111d932011-04-15 00:35:48 +0000973 E = E->IgnoreParens();
974
Ted Kremenekd30ef872009-01-12 23:09:09 +0000975 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000976 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000977 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000978 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000979 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
980 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000981 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000982 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000983 }
984
Ted Kremenek95355bb2010-09-09 03:51:42 +0000985 case Stmt::IntegerLiteralClass:
986 // Technically -Wformat-nonliteral does not warn about this case.
987 // The behavior of printf and friends in this case is implementation
988 // dependent. Ideally if the format string cannot be null then
989 // it should have a 'nonnull' attribute in the function prototype.
990 return true;
991
Ted Kremenekd30ef872009-01-12 23:09:09 +0000992 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000993 E = cast<ImplicitCastExpr>(E)->getSubExpr();
994 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000995 }
996
John McCall56ca35d2011-02-17 10:25:35 +0000997 case Stmt::OpaqueValueExprClass:
998 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
999 E = src;
1000 goto tryAgain;
1001 }
1002 return false;
1003
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001004 case Stmt::PredefinedExprClass:
1005 // While __func__, etc., are technically not string literals, they
1006 // cannot contain format specifiers and thus are not a security
1007 // liability.
1008 return true;
1009
Ted Kremenek082d9362009-03-20 21:35:28 +00001010 case Stmt::DeclRefExprClass: {
1011 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 // As an exception, do not flag errors for variables binding to
1014 // const string literals.
1015 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1016 bool isConstant = false;
1017 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001018
Ted Kremenek082d9362009-03-20 21:35:28 +00001019 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1020 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001021 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001022 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001023 PT->getPointeeType().isConstant(Context);
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Ted Kremenek082d9362009-03-20 21:35:28 +00001026 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001027 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001028 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001029 HasVAListArg, format_idx, firstDataArg,
1030 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Anders Carlssond966a552009-06-28 19:55:58 +00001033 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1034 // special check to see if the format string is a function parameter
1035 // of the function calling the printf function. If the function
1036 // has an attribute indicating it is a printf-like function, then we
1037 // should suppress warnings concerning non-literals being used in a call
1038 // to a vprintf function. For example:
1039 //
1040 // void
1041 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1042 // va_list ap;
1043 // va_start(ap, fmt);
1044 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1045 // ...
1046 //
1047 //
1048 // FIXME: We don't have full attribute support yet, so just check to see
1049 // if the argument is a DeclRefExpr that references a parameter. We'll
1050 // add proper support for checking the attribute later.
1051 if (HasVAListArg)
1052 if (isa<ParmVarDecl>(VD))
1053 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001054 }
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Ted Kremenek082d9362009-03-20 21:35:28 +00001056 return false;
1057 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001058
Anders Carlsson8f031b32009-06-27 04:05:33 +00001059 case Stmt::CallExprClass: {
1060 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001061 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001062 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1063 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1064 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001065 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001066 unsigned ArgIndex = FA->getFormatIdx();
1067 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
1069 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001070 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001071 }
1072 }
1073 }
1074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Anders Carlsson8f031b32009-06-27 04:05:33 +00001076 return false;
1077 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001078 case Stmt::ObjCStringLiteralClass:
1079 case Stmt::StringLiteralClass: {
1080 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Ted Kremenek082d9362009-03-20 21:35:28 +00001082 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001083 StrE = ObjCFExpr->getString();
1084 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001085 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Ted Kremenekd30ef872009-01-12 23:09:09 +00001087 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001088 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1089 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001090 return true;
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Ted Kremenekd30ef872009-01-12 23:09:09 +00001093 return false;
1094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Ted Kremenek082d9362009-03-20 21:35:28 +00001096 default:
1097 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001098 }
1099}
1100
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001101void
Mike Stump1eb44332009-09-09 15:08:12 +00001102Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001103 const Expr * const *ExprArgs,
1104 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001105 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1106 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001107 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001108 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001109 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001110 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001111 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001112 }
1113}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001114
Ted Kremenek826a3452010-07-16 02:11:22 +00001115/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1116/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001117void
Ted Kremenek826a3452010-07-16 02:11:22 +00001118Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1119 unsigned format_idx, unsigned firstDataArg,
1120 bool isPrintf) {
1121
Ted Kremenek082d9362009-03-20 21:35:28 +00001122 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001123
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001124 // The way the format attribute works in GCC, the implicit this argument
1125 // of member functions is counted. However, it doesn't appear in our own
1126 // lists, so decrement format_idx in that case.
1127 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001128 const CXXMethodDecl *method_decl =
1129 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1130 if (method_decl && method_decl->isInstance()) {
1131 // Catch a format attribute mistakenly referring to the object argument.
1132 if (format_idx == 0)
1133 return;
1134 --format_idx;
1135 if(firstDataArg != 0)
1136 --firstDataArg;
1137 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001138 }
1139
Ted Kremenek826a3452010-07-16 02:11:22 +00001140 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001141 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001142 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001143 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001144 return;
1145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Ted Kremenek082d9362009-03-20 21:35:28 +00001147 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner59907c42007-08-10 20:18:51 +00001149 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001150 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001151 // Dynamically generated format strings are difficult to
1152 // automatically vet at compile time. Requiring that format strings
1153 // are string literals: (1) permits the checking of format strings by
1154 // the compiler and thereby (2) can practically remove the source of
1155 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001156
Mike Stump1eb44332009-09-09 15:08:12 +00001157 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001158 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001159 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001160 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001161 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001162 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001163 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001164
Chris Lattner655f1412009-04-29 04:59:47 +00001165 // If there are no arguments specified, warn with -Wformat-security, otherwise
1166 // warn only with -Wformat-nonliteral.
1167 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001168 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001169 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001170 << OrigFormatExpr->getSourceRange();
1171 else
Mike Stump1eb44332009-09-09 15:08:12 +00001172 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001173 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001174 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001175}
Ted Kremenek71895b92007-08-14 17:39:48 +00001176
Ted Kremeneke0e53132010-01-28 23:39:18 +00001177namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001178class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1179protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001180 Sema &S;
1181 const StringLiteral *FExpr;
1182 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001183 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001184 const unsigned NumDataArgs;
1185 const bool IsObjCLiteral;
1186 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001187 const bool HasVAListArg;
1188 const CallExpr *TheCall;
1189 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001190 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001191 bool usesPositionalArgs;
1192 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001193public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001194 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001195 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001196 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001197 const char *beg, bool hasVAListArg,
1198 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001199 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001200 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001201 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001202 IsObjCLiteral(isObjCLiteral), Beg(beg),
1203 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001204 TheCall(theCall), FormatIdx(formatIdx),
1205 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001206 CoveredArgs.resize(numDataArgs);
1207 CoveredArgs.reset();
1208 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001209
Ted Kremenek07d161f2010-01-29 01:50:07 +00001210 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001211
Ted Kremenek826a3452010-07-16 02:11:22 +00001212 void HandleIncompleteSpecifier(const char *startSpecifier,
1213 unsigned specifierLen);
1214
Ted Kremenekefaff192010-02-27 01:41:03 +00001215 virtual void HandleInvalidPosition(const char *startSpecifier,
1216 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001217 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001218
1219 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1220
Ted Kremeneke0e53132010-01-28 23:39:18 +00001221 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001222
Ted Kremenek826a3452010-07-16 02:11:22 +00001223protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001224 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1225 const char *startSpec,
1226 unsigned specifierLen,
1227 const char *csStart, unsigned csLen);
1228
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001229 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001230 CharSourceRange getSpecifierRange(const char *startSpecifier,
1231 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001232 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001233
Ted Kremenek0d277352010-01-29 01:06:55 +00001234 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001235
1236 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1237 const analyze_format_string::ConversionSpecifier &CS,
1238 const char *startSpecifier, unsigned specifierLen,
1239 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001240};
1241}
1242
Ted Kremenek826a3452010-07-16 02:11:22 +00001243SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001244 return OrigFormatExpr->getSourceRange();
1245}
1246
Ted Kremenek826a3452010-07-16 02:11:22 +00001247CharSourceRange CheckFormatHandler::
1248getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001249 SourceLocation Start = getLocationOfByte(startSpecifier);
1250 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1251
1252 // Advance the end SourceLocation by one due to half-open ranges.
1253 End = End.getFileLocWithOffset(1);
1254
1255 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001256}
1257
Ted Kremenek826a3452010-07-16 02:11:22 +00001258SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001259 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001260}
1261
Ted Kremenek826a3452010-07-16 02:11:22 +00001262void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1263 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001264 SourceLocation Loc = getLocationOfByte(startSpecifier);
1265 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001266 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001267}
1268
Ted Kremenekefaff192010-02-27 01:41:03 +00001269void
Ted Kremenek826a3452010-07-16 02:11:22 +00001270CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1271 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001272 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001273 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1274 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001275}
1276
Ted Kremenek826a3452010-07-16 02:11:22 +00001277void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001278 unsigned posLen) {
1279 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001280 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1281 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001282}
1283
Ted Kremenek826a3452010-07-16 02:11:22 +00001284void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001285 if (!IsObjCLiteral) {
1286 // The presence of a null character is likely an error.
1287 S.Diag(getLocationOfByte(nullCharacter),
1288 diag::warn_printf_format_string_contains_null_char)
1289 << getFormatStringRange();
1290 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001291}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001292
Ted Kremenek826a3452010-07-16 02:11:22 +00001293const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1294 return TheCall->getArg(FirstDataArg + i);
1295}
1296
1297void CheckFormatHandler::DoneProcessing() {
1298 // Does the number of data arguments exceed the number of
1299 // format conversions in the format string?
1300 if (!HasVAListArg) {
1301 // Find any arguments that weren't covered.
1302 CoveredArgs.flip();
1303 signed notCoveredArg = CoveredArgs.find_first();
1304 if (notCoveredArg >= 0) {
1305 assert((unsigned)notCoveredArg < NumDataArgs);
1306 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1307 diag::warn_printf_data_arg_not_used)
1308 << getFormatStringRange();
1309 }
1310 }
1311}
1312
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001313bool
1314CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1315 SourceLocation Loc,
1316 const char *startSpec,
1317 unsigned specifierLen,
1318 const char *csStart,
1319 unsigned csLen) {
1320
1321 bool keepGoing = true;
1322 if (argIndex < NumDataArgs) {
1323 // Consider the argument coverered, even though the specifier doesn't
1324 // make sense.
1325 CoveredArgs.set(argIndex);
1326 }
1327 else {
1328 // If argIndex exceeds the number of data arguments we
1329 // don't issue a warning because that is just a cascade of warnings (and
1330 // they may have intended '%%' anyway). We don't want to continue processing
1331 // the format string after this point, however, as we will like just get
1332 // gibberish when trying to match arguments.
1333 keepGoing = false;
1334 }
1335
1336 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001337 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001338 << getSpecifierRange(startSpec, specifierLen);
1339
1340 return keepGoing;
1341}
1342
Ted Kremenek666a1972010-07-26 19:45:42 +00001343bool
1344CheckFormatHandler::CheckNumArgs(
1345 const analyze_format_string::FormatSpecifier &FS,
1346 const analyze_format_string::ConversionSpecifier &CS,
1347 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1348
1349 if (argIndex >= NumDataArgs) {
1350 if (FS.usesPositionalArg()) {
1351 S.Diag(getLocationOfByte(CS.getStart()),
1352 diag::warn_printf_positional_arg_exceeds_data_args)
1353 << (argIndex+1) << NumDataArgs
1354 << getSpecifierRange(startSpecifier, specifierLen);
1355 }
1356 else {
1357 S.Diag(getLocationOfByte(CS.getStart()),
1358 diag::warn_printf_insufficient_data_args)
1359 << getSpecifierRange(startSpecifier, specifierLen);
1360 }
1361
1362 return false;
1363 }
1364 return true;
1365}
1366
Ted Kremenek826a3452010-07-16 02:11:22 +00001367//===--- CHECK: Printf format string checking ------------------------------===//
1368
1369namespace {
1370class CheckPrintfHandler : public CheckFormatHandler {
1371public:
1372 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1373 const Expr *origFormatExpr, unsigned firstDataArg,
1374 unsigned numDataArgs, bool isObjCLiteral,
1375 const char *beg, bool hasVAListArg,
1376 const CallExpr *theCall, unsigned formatIdx)
1377 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1378 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1379 theCall, formatIdx) {}
1380
1381
1382 bool HandleInvalidPrintfConversionSpecifier(
1383 const analyze_printf::PrintfSpecifier &FS,
1384 const char *startSpecifier,
1385 unsigned specifierLen);
1386
1387 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1388 const char *startSpecifier,
1389 unsigned specifierLen);
1390
1391 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1392 const char *startSpecifier, unsigned specifierLen);
1393 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1394 const analyze_printf::OptionalAmount &Amt,
1395 unsigned type,
1396 const char *startSpecifier, unsigned specifierLen);
1397 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1398 const analyze_printf::OptionalFlag &flag,
1399 const char *startSpecifier, unsigned specifierLen);
1400 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1401 const analyze_printf::OptionalFlag &ignoredFlag,
1402 const analyze_printf::OptionalFlag &flag,
1403 const char *startSpecifier, unsigned specifierLen);
1404};
1405}
1406
1407bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1408 const analyze_printf::PrintfSpecifier &FS,
1409 const char *startSpecifier,
1410 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001411 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001412 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001413
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001414 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1415 getLocationOfByte(CS.getStart()),
1416 startSpecifier, specifierLen,
1417 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001418}
1419
Ted Kremenek826a3452010-07-16 02:11:22 +00001420bool CheckPrintfHandler::HandleAmount(
1421 const analyze_format_string::OptionalAmount &Amt,
1422 unsigned k, const char *startSpecifier,
1423 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001424
1425 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001426 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001427 unsigned argIndex = Amt.getArgIndex();
1428 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001429 S.Diag(getLocationOfByte(Amt.getStart()),
1430 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001431 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001432 // Don't do any more checking. We will just emit
1433 // spurious errors.
1434 return false;
1435 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001436
Ted Kremenek0d277352010-01-29 01:06:55 +00001437 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001438 // Although not in conformance with C99, we also allow the argument to be
1439 // an 'unsigned int' as that is a reasonably safe case. GCC also
1440 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001441 CoveredArgs.set(argIndex);
1442 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001443 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001444
1445 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1446 assert(ATR.isValid());
1447
1448 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001449 S.Diag(getLocationOfByte(Amt.getStart()),
1450 diag::warn_printf_asterisk_wrong_type)
1451 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001452 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001453 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001454 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001455 // Don't do any more checking. We will just emit
1456 // spurious errors.
1457 return false;
1458 }
1459 }
1460 }
1461 return true;
1462}
Ted Kremenek0d277352010-01-29 01:06:55 +00001463
Tom Caree4ee9662010-06-17 19:00:27 +00001464void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001465 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001466 const analyze_printf::OptionalAmount &Amt,
1467 unsigned type,
1468 const char *startSpecifier,
1469 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001470 const analyze_printf::PrintfConversionSpecifier &CS =
1471 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001472 switch (Amt.getHowSpecified()) {
1473 case analyze_printf::OptionalAmount::Constant:
1474 S.Diag(getLocationOfByte(Amt.getStart()),
1475 diag::warn_printf_nonsensical_optional_amount)
1476 << type
1477 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001478 << getSpecifierRange(startSpecifier, specifierLen)
1479 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001480 Amt.getConstantLength()));
1481 break;
1482
1483 default:
1484 S.Diag(getLocationOfByte(Amt.getStart()),
1485 diag::warn_printf_nonsensical_optional_amount)
1486 << type
1487 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001488 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001489 break;
1490 }
1491}
1492
Ted Kremenek826a3452010-07-16 02:11:22 +00001493void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001494 const analyze_printf::OptionalFlag &flag,
1495 const char *startSpecifier,
1496 unsigned specifierLen) {
1497 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001498 const analyze_printf::PrintfConversionSpecifier &CS =
1499 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001500 S.Diag(getLocationOfByte(flag.getPosition()),
1501 diag::warn_printf_nonsensical_flag)
1502 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001503 << getSpecifierRange(startSpecifier, specifierLen)
1504 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001505}
1506
1507void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001508 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001509 const analyze_printf::OptionalFlag &ignoredFlag,
1510 const analyze_printf::OptionalFlag &flag,
1511 const char *startSpecifier,
1512 unsigned specifierLen) {
1513 // Warn about ignored flag with a fixit removal.
1514 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1515 diag::warn_printf_ignored_flag)
1516 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001517 << getSpecifierRange(startSpecifier, specifierLen)
1518 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001519 ignoredFlag.getPosition(), 1));
1520}
1521
Ted Kremeneke0e53132010-01-28 23:39:18 +00001522bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001523CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001524 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001525 const char *startSpecifier,
1526 unsigned specifierLen) {
1527
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001528 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001529 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001530 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001531
Ted Kremenekbaa40062010-07-19 22:01:06 +00001532 if (FS.consumesDataArgument()) {
1533 if (atFirstArg) {
1534 atFirstArg = false;
1535 usesPositionalArgs = FS.usesPositionalArg();
1536 }
1537 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1538 // Cannot mix-and-match positional and non-positional arguments.
1539 S.Diag(getLocationOfByte(CS.getStart()),
1540 diag::warn_format_mix_positional_nonpositional_args)
1541 << getSpecifierRange(startSpecifier, specifierLen);
1542 return false;
1543 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001544 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001545
Ted Kremenekefaff192010-02-27 01:41:03 +00001546 // First check if the field width, precision, and conversion specifier
1547 // have matching data arguments.
1548 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1549 startSpecifier, specifierLen)) {
1550 return false;
1551 }
1552
1553 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1554 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001555 return false;
1556 }
1557
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001558 if (!CS.consumesDataArgument()) {
1559 // FIXME: Technically specifying a precision or field width here
1560 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001561 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001562 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001563
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001564 // Consume the argument.
1565 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001566 if (argIndex < NumDataArgs) {
1567 // The check to see if the argIndex is valid will come later.
1568 // We set the bit here because we may exit early from this
1569 // function if we encounter some other error.
1570 CoveredArgs.set(argIndex);
1571 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001572
1573 // Check for using an Objective-C specific conversion specifier
1574 // in a non-ObjC literal.
1575 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001576 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1577 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001578 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001579
Tom Caree4ee9662010-06-17 19:00:27 +00001580 // Check for invalid use of field width
1581 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001582 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001583 startSpecifier, specifierLen);
1584 }
1585
1586 // Check for invalid use of precision
1587 if (!FS.hasValidPrecision()) {
1588 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1589 startSpecifier, specifierLen);
1590 }
1591
1592 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001593 if (!FS.hasValidThousandsGroupingPrefix())
1594 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001595 if (!FS.hasValidLeadingZeros())
1596 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1597 if (!FS.hasValidPlusPrefix())
1598 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001599 if (!FS.hasValidSpacePrefix())
1600 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001601 if (!FS.hasValidAlternativeForm())
1602 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1603 if (!FS.hasValidLeftJustified())
1604 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1605
1606 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001607 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1608 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1609 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001610 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1611 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1612 startSpecifier, specifierLen);
1613
1614 // Check the length modifier is valid with the given conversion specifier.
1615 const LengthModifier &LM = FS.getLengthModifier();
1616 if (!FS.hasValidLengthModifier())
1617 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001618 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001619 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001620 << getSpecifierRange(startSpecifier, specifierLen)
1621 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001622 LM.getLength()));
1623
1624 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001625 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001626 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001627 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001628 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001629 // Continue checking the other format specifiers.
1630 return true;
1631 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001632
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001633 // The remaining checks depend on the data arguments.
1634 if (HasVAListArg)
1635 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001636
Ted Kremenek666a1972010-07-26 19:45:42 +00001637 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001638 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001639
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001640 // Now type check the data expression that matches the
1641 // format specifier.
1642 const Expr *Ex = getDataArg(argIndex);
1643 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1644 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1645 // Check if we didn't match because of an implicit cast from a 'char'
1646 // or 'short' to an 'int'. This is done because printf is a varargs
1647 // function.
1648 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001649 if (ICE->getType() == S.Context.IntTy) {
1650 // All further checking is done on the subexpression.
1651 Ex = ICE->getSubExpr();
1652 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001653 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001654 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001655
1656 // We may be able to offer a FixItHint if it is a supported type.
1657 PrintfSpecifier fixedFS = FS;
1658 bool success = fixedFS.fixType(Ex->getType());
1659
1660 if (success) {
1661 // Get the fix string from the fixed format specifier
1662 llvm::SmallString<128> buf;
1663 llvm::raw_svector_ostream os(buf);
1664 fixedFS.toString(os);
1665
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001666 // FIXME: getRepresentativeType() perhaps should return a string
1667 // instead of a QualType to better handle when the representative
1668 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001669 S.Diag(getLocationOfByte(CS.getStart()),
1670 diag::warn_printf_conversion_argument_type_mismatch)
1671 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1672 << getSpecifierRange(startSpecifier, specifierLen)
1673 << Ex->getSourceRange()
1674 << FixItHint::CreateReplacement(
1675 getSpecifierRange(startSpecifier, specifierLen),
1676 os.str());
1677 }
1678 else {
1679 S.Diag(getLocationOfByte(CS.getStart()),
1680 diag::warn_printf_conversion_argument_type_mismatch)
1681 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1682 << getSpecifierRange(startSpecifier, specifierLen)
1683 << Ex->getSourceRange();
1684 }
1685 }
1686
Ted Kremeneke0e53132010-01-28 23:39:18 +00001687 return true;
1688}
1689
Ted Kremenek826a3452010-07-16 02:11:22 +00001690//===--- CHECK: Scanf format string checking ------------------------------===//
1691
1692namespace {
1693class CheckScanfHandler : public CheckFormatHandler {
1694public:
1695 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1696 const Expr *origFormatExpr, unsigned firstDataArg,
1697 unsigned numDataArgs, bool isObjCLiteral,
1698 const char *beg, bool hasVAListArg,
1699 const CallExpr *theCall, unsigned formatIdx)
1700 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1701 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1702 theCall, formatIdx) {}
1703
1704 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1705 const char *startSpecifier,
1706 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001707
1708 bool HandleInvalidScanfConversionSpecifier(
1709 const analyze_scanf::ScanfSpecifier &FS,
1710 const char *startSpecifier,
1711 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001712
1713 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001714};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001715}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001716
Ted Kremenekb7c21012010-07-16 18:28:03 +00001717void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1718 const char *end) {
1719 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1720 << getSpecifierRange(start, end - start);
1721}
1722
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001723bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1724 const analyze_scanf::ScanfSpecifier &FS,
1725 const char *startSpecifier,
1726 unsigned specifierLen) {
1727
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001728 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001729 FS.getConversionSpecifier();
1730
1731 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1732 getLocationOfByte(CS.getStart()),
1733 startSpecifier, specifierLen,
1734 CS.getStart(), CS.getLength());
1735}
1736
Ted Kremenek826a3452010-07-16 02:11:22 +00001737bool CheckScanfHandler::HandleScanfSpecifier(
1738 const analyze_scanf::ScanfSpecifier &FS,
1739 const char *startSpecifier,
1740 unsigned specifierLen) {
1741
1742 using namespace analyze_scanf;
1743 using namespace analyze_format_string;
1744
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001745 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001746
Ted Kremenekbaa40062010-07-19 22:01:06 +00001747 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1748 // be used to decide if we are using positional arguments consistently.
1749 if (FS.consumesDataArgument()) {
1750 if (atFirstArg) {
1751 atFirstArg = false;
1752 usesPositionalArgs = FS.usesPositionalArg();
1753 }
1754 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1755 // Cannot mix-and-match positional and non-positional arguments.
1756 S.Diag(getLocationOfByte(CS.getStart()),
1757 diag::warn_format_mix_positional_nonpositional_args)
1758 << getSpecifierRange(startSpecifier, specifierLen);
1759 return false;
1760 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001761 }
1762
1763 // Check if the field with is non-zero.
1764 const OptionalAmount &Amt = FS.getFieldWidth();
1765 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1766 if (Amt.getConstantAmount() == 0) {
1767 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1768 Amt.getConstantLength());
1769 S.Diag(getLocationOfByte(Amt.getStart()),
1770 diag::warn_scanf_nonzero_width)
1771 << R << FixItHint::CreateRemoval(R);
1772 }
1773 }
1774
1775 if (!FS.consumesDataArgument()) {
1776 // FIXME: Technically specifying a precision or field width here
1777 // makes no sense. Worth issuing a warning at some point.
1778 return true;
1779 }
1780
1781 // Consume the argument.
1782 unsigned argIndex = FS.getArgIndex();
1783 if (argIndex < NumDataArgs) {
1784 // The check to see if the argIndex is valid will come later.
1785 // We set the bit here because we may exit early from this
1786 // function if we encounter some other error.
1787 CoveredArgs.set(argIndex);
1788 }
1789
Ted Kremenek1e51c202010-07-20 20:04:47 +00001790 // Check the length modifier is valid with the given conversion specifier.
1791 const LengthModifier &LM = FS.getLengthModifier();
1792 if (!FS.hasValidLengthModifier()) {
1793 S.Diag(getLocationOfByte(LM.getStart()),
1794 diag::warn_format_nonsensical_length)
1795 << LM.toString() << CS.toString()
1796 << getSpecifierRange(startSpecifier, specifierLen)
1797 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1798 LM.getLength()));
1799 }
1800
Ted Kremenek826a3452010-07-16 02:11:22 +00001801 // The remaining checks depend on the data arguments.
1802 if (HasVAListArg)
1803 return true;
1804
Ted Kremenek666a1972010-07-26 19:45:42 +00001805 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001806 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001807
1808 // FIXME: Check that the argument type matches the format specifier.
1809
1810 return true;
1811}
1812
1813void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001814 const Expr *OrigFormatExpr,
1815 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001816 unsigned format_idx, unsigned firstDataArg,
1817 bool isPrintf) {
1818
Ted Kremeneke0e53132010-01-28 23:39:18 +00001819 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00001820 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001821 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001822 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001823 << OrigFormatExpr->getSourceRange();
1824 return;
1825 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001826
Ted Kremeneke0e53132010-01-28 23:39:18 +00001827 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00001828 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001829 const char *Str = StrRef.data();
1830 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001831
Ted Kremeneke0e53132010-01-28 23:39:18 +00001832 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001833 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001834 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001835 << OrigFormatExpr->getSourceRange();
1836 return;
1837 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001838
1839 if (isPrintf) {
1840 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1841 TheCall->getNumArgs() - firstDataArg,
1842 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1843 HasVAListArg, TheCall, format_idx);
1844
1845 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1846 H.DoneProcessing();
1847 }
1848 else {
1849 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1850 TheCall->getNumArgs() - firstDataArg,
1851 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1852 HasVAListArg, TheCall, format_idx);
1853
1854 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1855 H.DoneProcessing();
1856 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001857}
1858
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001859//===--- CHECK: Standard memory functions ---------------------------------===//
1860
Douglas Gregor2a053a32011-05-03 20:05:22 +00001861/// \brief Determine whether the given type is a dynamic class type (e.g.,
1862/// whether it has a vtable).
1863static bool isDynamicClassType(QualType T) {
1864 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1865 if (CXXRecordDecl *Definition = Record->getDefinition())
1866 if (Definition->isDynamicClass())
1867 return true;
1868
1869 return false;
1870}
1871
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001872/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00001873/// otherwise returns NULL.
1874static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001875 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001876 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1877 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1878 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001879
Chandler Carruth000d4282011-06-16 09:09:40 +00001880 return 0;
1881}
1882
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001883/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00001884static QualType getSizeOfArgType(const Expr* E) {
1885 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1886 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1887 if (SizeOf->getKind() == clang::UETT_SizeOf)
1888 return SizeOf->getTypeOfArgument();
1889
1890 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001891}
1892
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001893/// \brief Check for dangerous or invalid arguments to memset().
1894///
Chandler Carruth929f0132011-06-03 06:23:57 +00001895/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001896/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
1897/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001898///
1899/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001900void Sema::CheckMemaccessArguments(const CallExpr *Call,
1901 CheckedMemoryFunction CMF,
1902 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001903 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00001904 // we have enough arguments, and if not, abort further checking.
1905 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001906 return;
1907
Douglas Gregor707a23e2011-06-16 17:56:04 +00001908 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00001909 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001910
1911 // We have special checking when the length is a sizeof expression.
1912 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1913 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1914 llvm::FoldingSetNodeID SizeOfArgID;
1915
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001916 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1917 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001918 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001919
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001920 QualType DestTy = Dest->getType();
1921 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1922 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001923
Chandler Carruth000d4282011-06-16 09:09:40 +00001924 // Never warn about void type pointers. This can be used to suppress
1925 // false positives.
1926 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001927 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001928
Chandler Carruth000d4282011-06-16 09:09:40 +00001929 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1930 // actually comparing the expressions for equality. Because computing the
1931 // expression IDs can be expensive, we only do this if the diagnostic is
1932 // enabled.
1933 if (SizeOfArg &&
1934 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1935 SizeOfArg->getExprLoc())) {
1936 // We only compute IDs for expressions if the warning is enabled, and
1937 // cache the sizeof arg's ID.
1938 if (SizeOfArgID == llvm::FoldingSetNodeID())
1939 SizeOfArg->Profile(SizeOfArgID, Context, true);
1940 llvm::FoldingSetNodeID DestID;
1941 Dest->Profile(DestID, Context, true);
1942 if (DestID == SizeOfArgID) {
1943 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1944 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1945 if (UnaryOp->getOpcode() == UO_AddrOf)
1946 ActionIdx = 1; // If its an address-of operator, just remove it.
1947 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1948 ActionIdx = 2; // If the pointee's size is sizeof(char),
1949 // suggest an explicit length.
1950 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1951 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1952 << FnName << ArgIdx << ActionIdx
1953 << Dest->getSourceRange()
1954 << SizeOfArg->getSourceRange());
1955 break;
1956 }
1957 }
1958
1959 // Also check for cases where the sizeof argument is the exact same
1960 // type as the memory argument, and where it points to a user-defined
1961 // record type.
1962 if (SizeOfArgTy != QualType()) {
1963 if (PointeeTy->isRecordType() &&
1964 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
1965 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
1966 PDiag(diag::warn_sizeof_pointer_type_memaccess)
1967 << FnName << SizeOfArgTy << ArgIdx
1968 << PointeeTy << Dest->getSourceRange()
1969 << LenExpr->getSourceRange());
1970 break;
1971 }
Nico Webere4a1c642011-06-14 16:14:58 +00001972 }
1973
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001974 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00001975 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00001976 DiagRuntimeBehavior(
1977 Dest->getExprLoc(), Dest,
1978 PDiag(diag::warn_dyn_class_memaccess)
1979 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
1980 // "overwritten" if we're warning about the destination for any call
1981 // but memcmp; otherwise a verb appropriate to the call.
1982 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
1983 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00001984 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00001985 DiagRuntimeBehavior(
1986 Dest->getExprLoc(), Dest,
1987 PDiag(diag::warn_arc_object_memaccess)
1988 << ArgIdx << FnName << PointeeTy
1989 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00001990 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001991 continue;
John McCallf85e1932011-06-15 23:02:42 +00001992
1993 DiagRuntimeBehavior(
1994 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00001995 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001996 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1997 break;
1998 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001999 }
2000}
2001
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002002// A little helper routine: ignore addition and subtraction of integer literals.
2003// This intentionally does not ignore all integer constant expressions because
2004// we don't want to remove sizeof().
2005static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2006 Ex = Ex->IgnoreParenCasts();
2007
2008 for (;;) {
2009 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2010 if (!BO || !BO->isAdditiveOp())
2011 break;
2012
2013 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2014 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2015
2016 if (isa<IntegerLiteral>(RHS))
2017 Ex = LHS;
2018 else if (isa<IntegerLiteral>(LHS))
2019 Ex = RHS;
2020 else
2021 break;
2022 }
2023
2024 return Ex;
2025}
2026
2027// Warn if the user has made the 'size' argument to strlcpy or strlcat
2028// be the size of the source, instead of the destination.
2029void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2030 IdentifierInfo *FnName) {
2031
2032 // Don't crash if the user has the wrong number of arguments
2033 if (Call->getNumArgs() != 3)
2034 return;
2035
2036 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2037 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2038 const Expr *CompareWithSrc = NULL;
2039
2040 // Look for 'strlcpy(dst, x, sizeof(x))'
2041 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2042 CompareWithSrc = Ex;
2043 else {
2044 // Look for 'strlcpy(dst, x, strlen(x))'
2045 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2046 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2047 && SizeCall->getNumArgs() == 1)
2048 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2049 }
2050 }
2051
2052 if (!CompareWithSrc)
2053 return;
2054
2055 // Determine if the argument to sizeof/strlen is equal to the source
2056 // argument. In principle there's all kinds of things you could do
2057 // here, for instance creating an == expression and evaluating it with
2058 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2059 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2060 if (!SrcArgDRE)
2061 return;
2062
2063 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2064 if (!CompareWithSrcDRE ||
2065 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2066 return;
2067
2068 const Expr *OriginalSizeArg = Call->getArg(2);
2069 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2070 << OriginalSizeArg->getSourceRange() << FnName;
2071
2072 // Output a FIXIT hint if the destination is an array (rather than a
2073 // pointer to an array). This could be enhanced to handle some
2074 // pointers if we know the actual size, like if DstArg is 'array+2'
2075 // we could say 'sizeof(array)-2'.
2076 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002077 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002078
Ted Kremenek8f746222011-08-18 22:48:41 +00002079 // Only handle constant-sized or VLAs, but not flexible members.
2080 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2081 // Only issue the FIXIT for arrays of size > 1.
2082 if (CAT->getSize().getSExtValue() <= 1)
2083 return;
2084 } else if (!DstArgTy->isVariableArrayType()) {
2085 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002086 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002087
2088 llvm::SmallString<128> sizeString;
2089 llvm::raw_svector_ostream OS(sizeString);
2090 OS << "sizeof(";
2091 DstArg->printPretty(OS, Context, 0, Context.PrintingPolicy);
2092 OS << ")";
2093
2094 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2095 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2096 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002097}
2098
Ted Kremenek06de2762007-08-17 16:46:58 +00002099//===--- CHECK: Return Address of Stack Variable --------------------------===//
2100
Chris Lattner5f9e2722011-07-23 10:55:15 +00002101static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2102static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002103
2104/// CheckReturnStackAddr - Check if a return statement returns the address
2105/// of a stack variable.
2106void
2107Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2108 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002110 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002111 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002112
2113 // Perform checking for returned stack addresses, local blocks,
2114 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002115 if (lhsType->isPointerType() ||
2116 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002117 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002118 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002119 stackE = EvalVal(RetValExp, refVars);
2120 }
2121
2122 if (stackE == 0)
2123 return; // Nothing suspicious was found.
2124
2125 SourceLocation diagLoc;
2126 SourceRange diagRange;
2127 if (refVars.empty()) {
2128 diagLoc = stackE->getLocStart();
2129 diagRange = stackE->getSourceRange();
2130 } else {
2131 // We followed through a reference variable. 'stackE' contains the
2132 // problematic expression but we will warn at the return statement pointing
2133 // at the reference variable. We will later display the "trail" of
2134 // reference variables using notes.
2135 diagLoc = refVars[0]->getLocStart();
2136 diagRange = refVars[0]->getSourceRange();
2137 }
2138
2139 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2140 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2141 : diag::warn_ret_stack_addr)
2142 << DR->getDecl()->getDeclName() << diagRange;
2143 } else if (isa<BlockExpr>(stackE)) { // local block.
2144 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2145 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2146 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2147 } else { // local temporary.
2148 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2149 : diag::warn_ret_local_temp_addr)
2150 << diagRange;
2151 }
2152
2153 // Display the "trail" of reference variables that we followed until we
2154 // found the problematic expression using notes.
2155 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2156 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2157 // If this var binds to another reference var, show the range of the next
2158 // var, otherwise the var binds to the problematic expression, in which case
2159 // show the range of the expression.
2160 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2161 : stackE->getSourceRange();
2162 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2163 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002164 }
2165}
2166
2167/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2168/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002169/// to a location on the stack, a local block, an address of a label, or a
2170/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002171/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002172/// encounter a subexpression that (1) clearly does not lead to one of the
2173/// above problematic expressions (2) is something we cannot determine leads to
2174/// a problematic expression based on such local checking.
2175///
2176/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2177/// the expression that they point to. Such variables are added to the
2178/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002179///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002180/// EvalAddr processes expressions that are pointers that are used as
2181/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002182/// At the base case of the recursion is a check for the above problematic
2183/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002184///
2185/// This implementation handles:
2186///
2187/// * pointer-to-pointer casts
2188/// * implicit conversions from array references to pointers
2189/// * taking the address of fields
2190/// * arbitrary interplay between "&" and "*" operators
2191/// * pointer arithmetic from an address of a stack variable
2192/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002193static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002194 if (E->isTypeDependent())
2195 return NULL;
2196
Ted Kremenek06de2762007-08-17 16:46:58 +00002197 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002198 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002199 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002200 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002201 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Peter Collingbournef111d932011-04-15 00:35:48 +00002203 E = E->IgnoreParens();
2204
Ted Kremenek06de2762007-08-17 16:46:58 +00002205 // Our "symbolic interpreter" is just a dispatch off the currently
2206 // viewed AST node. We then recursively traverse the AST by calling
2207 // EvalAddr and EvalVal appropriately.
2208 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002209 case Stmt::DeclRefExprClass: {
2210 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2211
2212 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2213 // If this is a reference variable, follow through to the expression that
2214 // it points to.
2215 if (V->hasLocalStorage() &&
2216 V->getType()->isReferenceType() && V->hasInit()) {
2217 // Add the reference variable to the "trail".
2218 refVars.push_back(DR);
2219 return EvalAddr(V->getInit(), refVars);
2220 }
2221
2222 return NULL;
2223 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002224
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002225 case Stmt::UnaryOperatorClass: {
2226 // The only unary operator that make sense to handle here
2227 // is AddrOf. All others don't make sense as pointers.
2228 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
John McCall2de56d12010-08-25 11:45:40 +00002230 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002231 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002232 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002233 return NULL;
2234 }
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002236 case Stmt::BinaryOperatorClass: {
2237 // Handle pointer arithmetic. All other binary operators are not valid
2238 // in this context.
2239 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002240 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002241
John McCall2de56d12010-08-25 11:45:40 +00002242 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002243 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002245 Expr *Base = B->getLHS();
2246
2247 // Determine which argument is the real pointer base. It could be
2248 // the RHS argument instead of the LHS.
2249 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002251 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002252 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002253 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002254
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002255 // For conditional operators we need to see if either the LHS or RHS are
2256 // valid DeclRefExpr*s. If one of them is valid, we return it.
2257 case Stmt::ConditionalOperatorClass: {
2258 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002260 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002261 if (Expr *lhsExpr = C->getLHS()) {
2262 // In C++, we can have a throw-expression, which has 'void' type.
2263 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002264 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002265 return LHS;
2266 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002267
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002268 // In C++, we can have a throw-expression, which has 'void' type.
2269 if (C->getRHS()->getType()->isVoidType())
2270 return NULL;
2271
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002272 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002273 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002274
2275 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002276 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002277 return E; // local block.
2278 return NULL;
2279
2280 case Stmt::AddrLabelExprClass:
2281 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Ted Kremenek54b52742008-08-07 00:49:01 +00002283 // For casts, we need to handle conversions from arrays to
2284 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002285 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002286 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002287 case Stmt::CXXFunctionalCastExprClass:
2288 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002289 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002290 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Steve Naroffdd972f22008-09-05 22:11:13 +00002292 if (SubExpr->getType()->isPointerType() ||
2293 SubExpr->getType()->isBlockPointerType() ||
2294 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002295 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002296 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002297 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002298 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002299 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002300 }
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002302 // C++ casts. For dynamic casts, static casts, and const casts, we
2303 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002304 // through the cast. In the case the dynamic cast doesn't fail (and
2305 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002306 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002307 // FIXME: The comment about is wrong; we're not always converting
2308 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002309 // handle references to objects.
2310 case Stmt::CXXStaticCastExprClass:
2311 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002312 case Stmt::CXXConstCastExprClass:
2313 case Stmt::CXXReinterpretCastExprClass: {
2314 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002315 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002316 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002317 else
2318 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002319 }
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Douglas Gregor03e80032011-06-21 17:03:29 +00002321 case Stmt::MaterializeTemporaryExprClass:
2322 if (Expr *Result = EvalAddr(
2323 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2324 refVars))
2325 return Result;
2326
2327 return E;
2328
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002329 // Everything else: we simply don't reason about them.
2330 default:
2331 return NULL;
2332 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002333}
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Ted Kremenek06de2762007-08-17 16:46:58 +00002335
2336/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2337/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002338static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002339do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002340 // We should only be called for evaluating non-pointer expressions, or
2341 // expressions with a pointer type that are not used as references but instead
2342 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Ted Kremenek06de2762007-08-17 16:46:58 +00002344 // Our "symbolic interpreter" is just a dispatch off the currently
2345 // viewed AST node. We then recursively traverse the AST by calling
2346 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002347
2348 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002349 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002350 case Stmt::ImplicitCastExprClass: {
2351 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002352 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002353 E = IE->getSubExpr();
2354 continue;
2355 }
2356 return NULL;
2357 }
2358
Douglas Gregora2813ce2009-10-23 18:54:35 +00002359 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002360 // When we hit a DeclRefExpr we are looking at code that refers to a
2361 // variable's name. If it's not a reference variable we check if it has
2362 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002363 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Ted Kremenek06de2762007-08-17 16:46:58 +00002365 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002366 if (V->hasLocalStorage()) {
2367 if (!V->getType()->isReferenceType())
2368 return DR;
2369
2370 // Reference variable, follow through to the expression that
2371 // it points to.
2372 if (V->hasInit()) {
2373 // Add the reference variable to the "trail".
2374 refVars.push_back(DR);
2375 return EvalVal(V->getInit(), refVars);
2376 }
2377 }
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Ted Kremenek06de2762007-08-17 16:46:58 +00002379 return NULL;
2380 }
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Ted Kremenek06de2762007-08-17 16:46:58 +00002382 case Stmt::UnaryOperatorClass: {
2383 // The only unary operator that make sense to handle here
2384 // is Deref. All others don't resolve to a "name." This includes
2385 // handling all sorts of rvalues passed to a unary operator.
2386 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002387
John McCall2de56d12010-08-25 11:45:40 +00002388 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002389 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002390
2391 return NULL;
2392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Ted Kremenek06de2762007-08-17 16:46:58 +00002394 case Stmt::ArraySubscriptExprClass: {
2395 // Array subscripts are potential references to data on the stack. We
2396 // retrieve the DeclRefExpr* for the array variable if it indeed
2397 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002398 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Ted Kremenek06de2762007-08-17 16:46:58 +00002401 case Stmt::ConditionalOperatorClass: {
2402 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002403 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002404 ConditionalOperator *C = cast<ConditionalOperator>(E);
2405
Anders Carlsson39073232007-11-30 19:04:31 +00002406 // Handle the GNU extension for missing LHS.
2407 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002408 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002409 return LHS;
2410
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002411 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002412 }
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Ted Kremenek06de2762007-08-17 16:46:58 +00002414 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002415 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002416 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Ted Kremenek06de2762007-08-17 16:46:58 +00002418 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002419 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002420 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002421
2422 // Check whether the member type is itself a reference, in which case
2423 // we're not going to refer to the member, but to what the member refers to.
2424 if (M->getMemberDecl()->getType()->isReferenceType())
2425 return NULL;
2426
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002427 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Douglas Gregor03e80032011-06-21 17:03:29 +00002430 case Stmt::MaterializeTemporaryExprClass:
2431 if (Expr *Result = EvalVal(
2432 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2433 refVars))
2434 return Result;
2435
2436 return E;
2437
Ted Kremenek06de2762007-08-17 16:46:58 +00002438 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002439 // Check that we don't return or take the address of a reference to a
2440 // temporary. This is only useful in C++.
2441 if (!E->isTypeDependent() && E->isRValue())
2442 return E;
2443
2444 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002445 return NULL;
2446 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002447} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002448}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002449
2450//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2451
2452/// Check for comparisons of floating point operands using != and ==.
2453/// Issue a warning if these are no self-comparisons, as they are not likely
2454/// to do what the programmer intended.
2455void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2456 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002457
John McCallf6a16482010-12-04 03:47:34 +00002458 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2459 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002460
2461 // Special case: check for x == x (which is OK).
2462 // Do not emit warnings for such cases.
2463 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2464 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2465 if (DRL->getDecl() == DRR->getDecl())
2466 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002467
2468
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002469 // Special case: check for comparisons against literals that can be exactly
2470 // represented by APFloat. In such cases, do not emit a warning. This
2471 // is a heuristic: often comparison against such literals are used to
2472 // detect if a value in a variable has not changed. This clearly can
2473 // lead to false negatives.
2474 if (EmitWarning) {
2475 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2476 if (FLL->isExact())
2477 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002478 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002479 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2480 if (FLR->isExact())
2481 EmitWarning = false;
2482 }
2483 }
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002485 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002486 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002487 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002488 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002489 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Sebastian Redl0eb23302009-01-19 00:08:26 +00002491 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002492 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002493 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002494 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002496 // Emit the diagnostic.
2497 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002498 Diag(loc, diag::warn_floatingpoint_eq)
2499 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002500}
John McCallba26e582010-01-04 23:21:16 +00002501
John McCallf2370c92010-01-06 05:24:50 +00002502//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2503//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002504
John McCallf2370c92010-01-06 05:24:50 +00002505namespace {
John McCallba26e582010-01-04 23:21:16 +00002506
John McCallf2370c92010-01-06 05:24:50 +00002507/// Structure recording the 'active' range of an integer-valued
2508/// expression.
2509struct IntRange {
2510 /// The number of bits active in the int.
2511 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002512
John McCallf2370c92010-01-06 05:24:50 +00002513 /// True if the int is known not to have negative values.
2514 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002515
John McCallf2370c92010-01-06 05:24:50 +00002516 IntRange(unsigned Width, bool NonNegative)
2517 : Width(Width), NonNegative(NonNegative)
2518 {}
John McCallba26e582010-01-04 23:21:16 +00002519
John McCall1844a6e2010-11-10 23:38:19 +00002520 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002521 static IntRange forBoolType() {
2522 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002523 }
2524
John McCall1844a6e2010-11-10 23:38:19 +00002525 /// Returns the range of an opaque value of the given integral type.
2526 static IntRange forValueOfType(ASTContext &C, QualType T) {
2527 return forValueOfCanonicalType(C,
2528 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002529 }
2530
John McCall1844a6e2010-11-10 23:38:19 +00002531 /// Returns the range of an opaque value of a canonical integral type.
2532 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002533 assert(T->isCanonicalUnqualified());
2534
2535 if (const VectorType *VT = dyn_cast<VectorType>(T))
2536 T = VT->getElementType().getTypePtr();
2537 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2538 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002539
John McCall091f23f2010-11-09 22:22:12 +00002540 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002541 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2542 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002543 if (!Enum->isDefinition())
2544 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2545
John McCall323ed742010-05-06 08:58:33 +00002546 unsigned NumPositive = Enum->getNumPositiveBits();
2547 unsigned NumNegative = Enum->getNumNegativeBits();
2548
2549 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2550 }
John McCallf2370c92010-01-06 05:24:50 +00002551
2552 const BuiltinType *BT = cast<BuiltinType>(T);
2553 assert(BT->isInteger());
2554
2555 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2556 }
2557
John McCall1844a6e2010-11-10 23:38:19 +00002558 /// Returns the "target" range of a canonical integral type, i.e.
2559 /// the range of values expressible in the type.
2560 ///
2561 /// This matches forValueOfCanonicalType except that enums have the
2562 /// full range of their type, not the range of their enumerators.
2563 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2564 assert(T->isCanonicalUnqualified());
2565
2566 if (const VectorType *VT = dyn_cast<VectorType>(T))
2567 T = VT->getElementType().getTypePtr();
2568 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2569 T = CT->getElementType().getTypePtr();
2570 if (const EnumType *ET = dyn_cast<EnumType>(T))
2571 T = ET->getDecl()->getIntegerType().getTypePtr();
2572
2573 const BuiltinType *BT = cast<BuiltinType>(T);
2574 assert(BT->isInteger());
2575
2576 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2577 }
2578
2579 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002580 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002581 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002582 L.NonNegative && R.NonNegative);
2583 }
2584
John McCall1844a6e2010-11-10 23:38:19 +00002585 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002586 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002587 return IntRange(std::min(L.Width, R.Width),
2588 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002589 }
2590};
2591
2592IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2593 if (value.isSigned() && value.isNegative())
2594 return IntRange(value.getMinSignedBits(), false);
2595
2596 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002597 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002598
2599 // isNonNegative() just checks the sign bit without considering
2600 // signedness.
2601 return IntRange(value.getActiveBits(), true);
2602}
2603
John McCall0acc3112010-01-06 22:57:21 +00002604IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002605 unsigned MaxWidth) {
2606 if (result.isInt())
2607 return GetValueRange(C, result.getInt(), MaxWidth);
2608
2609 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002610 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2611 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2612 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2613 R = IntRange::join(R, El);
2614 }
John McCallf2370c92010-01-06 05:24:50 +00002615 return R;
2616 }
2617
2618 if (result.isComplexInt()) {
2619 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2620 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2621 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002622 }
2623
2624 // This can happen with lossless casts to intptr_t of "based" lvalues.
2625 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002626 // FIXME: The only reason we need to pass the type in here is to get
2627 // the sign right on this one case. It would be nice if APValue
2628 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002629 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002630 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002631}
John McCallf2370c92010-01-06 05:24:50 +00002632
2633/// Pseudo-evaluate the given integer expression, estimating the
2634/// range of values it might take.
2635///
2636/// \param MaxWidth - the width to which the value will be truncated
2637IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2638 E = E->IgnoreParens();
2639
2640 // Try a full evaluation first.
2641 Expr::EvalResult result;
2642 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002643 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002644
2645 // I think we only want to look through implicit casts here; if the
2646 // user has an explicit widening cast, we should treat the value as
2647 // being of the new, wider type.
2648 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002649 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002650 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2651
John McCall1844a6e2010-11-10 23:38:19 +00002652 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002653
John McCall2de56d12010-08-25 11:45:40 +00002654 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002655
John McCallf2370c92010-01-06 05:24:50 +00002656 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002657 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002658 return OutputTypeRange;
2659
2660 IntRange SubRange
2661 = GetExprRange(C, CE->getSubExpr(),
2662 std::min(MaxWidth, OutputTypeRange.Width));
2663
2664 // Bail out if the subexpr's range is as wide as the cast type.
2665 if (SubRange.Width >= OutputTypeRange.Width)
2666 return OutputTypeRange;
2667
2668 // Otherwise, we take the smaller width, and we're non-negative if
2669 // either the output type or the subexpr is.
2670 return IntRange(SubRange.Width,
2671 SubRange.NonNegative || OutputTypeRange.NonNegative);
2672 }
2673
2674 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2675 // If we can fold the condition, just take that operand.
2676 bool CondResult;
2677 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2678 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2679 : CO->getFalseExpr(),
2680 MaxWidth);
2681
2682 // Otherwise, conservatively merge.
2683 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2684 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2685 return IntRange::join(L, R);
2686 }
2687
2688 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2689 switch (BO->getOpcode()) {
2690
2691 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002692 case BO_LAnd:
2693 case BO_LOr:
2694 case BO_LT:
2695 case BO_GT:
2696 case BO_LE:
2697 case BO_GE:
2698 case BO_EQ:
2699 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002700 return IntRange::forBoolType();
2701
John McCall862ff872011-07-13 06:35:24 +00002702 // The type of the assignments is the type of the LHS, so the RHS
2703 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002704 case BO_MulAssign:
2705 case BO_DivAssign:
2706 case BO_RemAssign:
2707 case BO_AddAssign:
2708 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002709 case BO_XorAssign:
2710 case BO_OrAssign:
2711 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002712 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002713
John McCall862ff872011-07-13 06:35:24 +00002714 // Simple assignments just pass through the RHS, which will have
2715 // been coerced to the LHS type.
2716 case BO_Assign:
2717 // TODO: bitfields?
2718 return GetExprRange(C, BO->getRHS(), MaxWidth);
2719
John McCallf2370c92010-01-06 05:24:50 +00002720 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002721 case BO_PtrMemD:
2722 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002723 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002724
John McCall60fad452010-01-06 22:07:33 +00002725 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002726 case BO_And:
2727 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002728 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2729 GetExprRange(C, BO->getRHS(), MaxWidth));
2730
John McCallf2370c92010-01-06 05:24:50 +00002731 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002732 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002733 // ...except that we want to treat '1 << (blah)' as logically
2734 // positive. It's an important idiom.
2735 if (IntegerLiteral *I
2736 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2737 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002738 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002739 return IntRange(R.Width, /*NonNegative*/ true);
2740 }
2741 }
2742 // fallthrough
2743
John McCall2de56d12010-08-25 11:45:40 +00002744 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002745 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002746
John McCall60fad452010-01-06 22:07:33 +00002747 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002748 case BO_Shr:
2749 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002750 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2751
2752 // If the shift amount is a positive constant, drop the width by
2753 // that much.
2754 llvm::APSInt shift;
2755 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2756 shift.isNonNegative()) {
2757 unsigned zext = shift.getZExtValue();
2758 if (zext >= L.Width)
2759 L.Width = (L.NonNegative ? 0 : 1);
2760 else
2761 L.Width -= zext;
2762 }
2763
2764 return L;
2765 }
2766
2767 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002768 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002769 return GetExprRange(C, BO->getRHS(), MaxWidth);
2770
John McCall60fad452010-01-06 22:07:33 +00002771 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002772 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002773 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002774 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00002775 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002776
John McCall00fe7612011-07-14 22:39:48 +00002777 // The width of a division result is mostly determined by the size
2778 // of the LHS.
2779 case BO_Div: {
2780 // Don't 'pre-truncate' the operands.
2781 unsigned opWidth = C.getIntWidth(E->getType());
2782 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2783
2784 // If the divisor is constant, use that.
2785 llvm::APSInt divisor;
2786 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
2787 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
2788 if (log2 >= L.Width)
2789 L.Width = (L.NonNegative ? 0 : 1);
2790 else
2791 L.Width = std::min(L.Width - log2, MaxWidth);
2792 return L;
2793 }
2794
2795 // Otherwise, just use the LHS's width.
2796 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2797 return IntRange(L.Width, L.NonNegative && R.NonNegative);
2798 }
2799
2800 // The result of a remainder can't be larger than the result of
2801 // either side.
2802 case BO_Rem: {
2803 // Don't 'pre-truncate' the operands.
2804 unsigned opWidth = C.getIntWidth(E->getType());
2805 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2806 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2807
2808 IntRange meet = IntRange::meet(L, R);
2809 meet.Width = std::min(meet.Width, MaxWidth);
2810 return meet;
2811 }
2812
2813 // The default behavior is okay for these.
2814 case BO_Mul:
2815 case BO_Add:
2816 case BO_Xor:
2817 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00002818 break;
2819 }
2820
John McCall00fe7612011-07-14 22:39:48 +00002821 // The default case is to treat the operation as if it were closed
2822 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00002823 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2824 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2825 return IntRange::join(L, R);
2826 }
2827
2828 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2829 switch (UO->getOpcode()) {
2830 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002831 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002832 return IntRange::forBoolType();
2833
2834 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002835 case UO_Deref:
2836 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002837 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002838
2839 default:
2840 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2841 }
2842 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002843
2844 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002845 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002846 }
John McCallf2370c92010-01-06 05:24:50 +00002847
2848 FieldDecl *BitField = E->getBitField();
2849 if (BitField) {
2850 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2851 unsigned BitWidth = BitWidthAP.getZExtValue();
2852
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002853 return IntRange(BitWidth,
2854 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002855 }
2856
John McCall1844a6e2010-11-10 23:38:19 +00002857 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002858}
John McCall51313c32010-01-04 23:31:57 +00002859
John McCall323ed742010-05-06 08:58:33 +00002860IntRange GetExprRange(ASTContext &C, Expr *E) {
2861 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2862}
2863
John McCall51313c32010-01-04 23:31:57 +00002864/// Checks whether the given value, which currently has the given
2865/// source semantics, has the same value when coerced through the
2866/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002867bool IsSameFloatAfterCast(const llvm::APFloat &value,
2868 const llvm::fltSemantics &Src,
2869 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002870 llvm::APFloat truncated = value;
2871
2872 bool ignored;
2873 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2874 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2875
2876 return truncated.bitwiseIsEqual(value);
2877}
2878
2879/// Checks whether the given value, which currently has the given
2880/// source semantics, has the same value when coerced through the
2881/// target semantics.
2882///
2883/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002884bool IsSameFloatAfterCast(const APValue &value,
2885 const llvm::fltSemantics &Src,
2886 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002887 if (value.isFloat())
2888 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2889
2890 if (value.isVector()) {
2891 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2892 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2893 return false;
2894 return true;
2895 }
2896
2897 assert(value.isComplexFloat());
2898 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2899 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2900}
2901
John McCallb4eb64d2010-10-08 02:01:28 +00002902void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002903
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002904static bool IsZero(Sema &S, Expr *E) {
2905 // Suppress cases where we are comparing against an enum constant.
2906 if (const DeclRefExpr *DR =
2907 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2908 if (isa<EnumConstantDecl>(DR->getDecl()))
2909 return false;
2910
2911 // Suppress cases where the '0' value is expanded from a macro.
2912 if (E->getLocStart().isMacroID())
2913 return false;
2914
John McCall323ed742010-05-06 08:58:33 +00002915 llvm::APSInt Value;
2916 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2917}
2918
John McCall372e1032010-10-06 00:25:24 +00002919static bool HasEnumType(Expr *E) {
2920 // Strip off implicit integral promotions.
2921 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002922 if (ICE->getCastKind() != CK_IntegralCast &&
2923 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002924 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002925 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002926 }
2927
2928 return E->getType()->isEnumeralType();
2929}
2930
John McCall323ed742010-05-06 08:58:33 +00002931void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002932 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002933 if (E->isValueDependent())
2934 return;
2935
John McCall2de56d12010-08-25 11:45:40 +00002936 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002937 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002938 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002939 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002940 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002941 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002942 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002943 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002944 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002945 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002946 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002947 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002948 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002949 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002950 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002951 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2952 }
2953}
2954
2955/// Analyze the operands of the given comparison. Implements the
2956/// fallback case from AnalyzeComparison.
2957void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002958 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2959 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002960}
John McCall51313c32010-01-04 23:31:57 +00002961
John McCallba26e582010-01-04 23:21:16 +00002962/// \brief Implements -Wsign-compare.
2963///
2964/// \param lex the left-hand expression
2965/// \param rex the right-hand expression
2966/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002967/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002968void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2969 // The type the comparison is being performed in.
2970 QualType T = E->getLHS()->getType();
2971 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2972 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002973
John McCall323ed742010-05-06 08:58:33 +00002974 // We don't do anything special if this isn't an unsigned integral
2975 // comparison: we're only interested in integral comparisons, and
2976 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002977 //
2978 // We also don't care about value-dependent expressions or expressions
2979 // whose result is a constant.
2980 if (!T->hasUnsignedIntegerRepresentation()
2981 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002982 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002983
John McCall323ed742010-05-06 08:58:33 +00002984 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2985 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002986
John McCall323ed742010-05-06 08:58:33 +00002987 // Check to see if one of the (unmodified) operands is of different
2988 // signedness.
2989 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002990 if (lex->getType()->hasSignedIntegerRepresentation()) {
2991 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002992 "unsigned comparison between two signed integer expressions?");
2993 signedOperand = lex;
2994 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002995 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002996 signedOperand = rex;
2997 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002998 } else {
John McCall323ed742010-05-06 08:58:33 +00002999 CheckTrivialUnsignedComparison(S, E);
3000 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003001 }
3002
John McCall323ed742010-05-06 08:58:33 +00003003 // Otherwise, calculate the effective range of the signed operand.
3004 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003005
John McCall323ed742010-05-06 08:58:33 +00003006 // Go ahead and analyze implicit conversions in the operands. Note
3007 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00003008 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
3009 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003010
John McCall323ed742010-05-06 08:58:33 +00003011 // If the signed range is non-negative, -Wsign-compare won't fire,
3012 // but we should still check for comparisons which are always true
3013 // or false.
3014 if (signedRange.NonNegative)
3015 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003016
3017 // For (in)equality comparisons, if the unsigned operand is a
3018 // constant which cannot collide with a overflowed signed operand,
3019 // then reinterpreting the signed operand as unsigned will not
3020 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003021 if (E->isEqualityOp()) {
3022 unsigned comparisonWidth = S.Context.getIntWidth(T);
3023 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003024
John McCall323ed742010-05-06 08:58:33 +00003025 // We should never be unable to prove that the unsigned operand is
3026 // non-negative.
3027 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3028
3029 if (unsignedRange.Width < comparisonWidth)
3030 return;
3031 }
3032
3033 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3034 << lex->getType() << rex->getType()
3035 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003036}
3037
John McCall15d7d122010-11-11 03:21:53 +00003038/// Analyzes an attempt to assign the given value to a bitfield.
3039///
3040/// Returns true if there was something fishy about the attempt.
3041bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3042 SourceLocation InitLoc) {
3043 assert(Bitfield->isBitField());
3044 if (Bitfield->isInvalidDecl())
3045 return false;
3046
John McCall91b60142010-11-11 05:33:51 +00003047 // White-list bool bitfields.
3048 if (Bitfield->getType()->isBooleanType())
3049 return false;
3050
Douglas Gregor46ff3032011-02-04 13:09:01 +00003051 // Ignore value- or type-dependent expressions.
3052 if (Bitfield->getBitWidth()->isValueDependent() ||
3053 Bitfield->getBitWidth()->isTypeDependent() ||
3054 Init->isValueDependent() ||
3055 Init->isTypeDependent())
3056 return false;
3057
John McCall15d7d122010-11-11 03:21:53 +00003058 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3059
3060 llvm::APSInt Width(32);
3061 Expr::EvalResult InitValue;
3062 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00003063 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003064 !InitValue.Val.isInt())
3065 return false;
3066
3067 const llvm::APSInt &Value = InitValue.Val.getInt();
3068 unsigned OriginalWidth = Value.getBitWidth();
3069 unsigned FieldWidth = Width.getZExtValue();
3070
3071 if (OriginalWidth <= FieldWidth)
3072 return false;
3073
Jay Foad9f71a8f2010-12-07 08:25:34 +00003074 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003075
3076 // It's fairly common to write values into signed bitfields
3077 // that, if sign-extended, would end up becoming a different
3078 // value. We don't want to warn about that.
3079 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003080 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003081 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003082 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003083
3084 if (Value == TruncatedValue)
3085 return false;
3086
3087 std::string PrettyValue = Value.toString(10);
3088 std::string PrettyTrunc = TruncatedValue.toString(10);
3089
3090 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3091 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3092 << Init->getSourceRange();
3093
3094 return true;
3095}
3096
John McCallbeb22aa2010-11-09 23:24:47 +00003097/// Analyze the given simple or compound assignment for warning-worthy
3098/// operations.
3099void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3100 // Just recurse on the LHS.
3101 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3102
3103 // We want to recurse on the RHS as normal unless we're assigning to
3104 // a bitfield.
3105 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003106 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3107 E->getOperatorLoc())) {
3108 // Recurse, ignoring any implicit conversions on the RHS.
3109 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3110 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003111 }
3112 }
3113
3114 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3115}
3116
John McCall51313c32010-01-04 23:31:57 +00003117/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003118void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3119 SourceLocation CContext, unsigned diag) {
3120 S.Diag(E->getExprLoc(), diag)
3121 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3122}
3123
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003124/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3125void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3126 unsigned diag) {
3127 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3128}
3129
Chandler Carruthf65076e2011-04-10 08:36:24 +00003130/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3131/// fixit hints when the cast wouldn't lose information to simply write the
3132/// expression with the expected type.
3133void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3134 SourceLocation CContext) {
3135 // Emit the primary warning first, then try to emit a fixit hint note if
3136 // reasonable.
3137 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3138 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3139
3140 const llvm::APFloat &Value = FL->getValue();
3141
3142 // Don't attempt to fix PPC double double literals.
3143 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3144 return;
3145
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003146 // Try to convert this exactly to an integer.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003147 bool isExact = false;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003148 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3149 T->hasUnsignedIntegerRepresentation());
3150 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003151 llvm::APFloat::rmTowardZero, &isExact)
3152 != llvm::APFloat::opOK || !isExact)
3153 return;
3154
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003155 std::string LiteralValue = IntegerValue.toString(10);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003156 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3157 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3158}
3159
John McCall091f23f2010-11-09 22:22:12 +00003160std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3161 if (!Range.Width) return "0";
3162
3163 llvm::APSInt ValueInRange = Value;
3164 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003165 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003166 return ValueInRange.toString(10);
3167}
3168
Ted Kremenekef9ff882011-03-10 20:03:42 +00003169static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3170 SourceManager &smgr = S.Context.getSourceManager();
3171 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3172}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003173
John McCall323ed742010-05-06 08:58:33 +00003174void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003175 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003176 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003177
John McCall323ed742010-05-06 08:58:33 +00003178 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3179 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3180 if (Source == Target) return;
3181 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003182
Chandler Carruth108f7562011-07-26 05:40:03 +00003183 // If the conversion context location is invalid don't complain. We also
3184 // don't want to emit a warning if the issue occurs from the expansion of
3185 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3186 // delay this check as long as possible. Once we detect we are in that
3187 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003188 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003189 return;
3190
John McCall51313c32010-01-04 23:31:57 +00003191 // Never diagnose implicit casts to bool.
3192 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3193 return;
3194
3195 // Strip vector types.
3196 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003197 if (!isa<VectorType>(Target)) {
3198 if (isFromSystemMacro(S, CC))
3199 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003200 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003201 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003202
3203 // If the vector cast is cast between two vectors of the same size, it is
3204 // a bitcast, not a conversion.
3205 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3206 return;
John McCall51313c32010-01-04 23:31:57 +00003207
3208 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3209 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3210 }
3211
3212 // Strip complex types.
3213 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003214 if (!isa<ComplexType>(Target)) {
3215 if (isFromSystemMacro(S, CC))
3216 return;
3217
John McCallb4eb64d2010-10-08 02:01:28 +00003218 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003219 }
John McCall51313c32010-01-04 23:31:57 +00003220
3221 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3222 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3223 }
3224
3225 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3226 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3227
3228 // If the source is floating point...
3229 if (SourceBT && SourceBT->isFloatingPoint()) {
3230 // ...and the target is floating point...
3231 if (TargetBT && TargetBT->isFloatingPoint()) {
3232 // ...then warn if we're dropping FP rank.
3233
3234 // Builtin FP kinds are ordered by increasing FP rank.
3235 if (SourceBT->getKind() > TargetBT->getKind()) {
3236 // Don't warn about float constants that are precisely
3237 // representable in the target type.
3238 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003239 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003240 // Value might be a float, a float vector, or a float complex.
3241 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003242 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3243 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003244 return;
3245 }
3246
Ted Kremenekef9ff882011-03-10 20:03:42 +00003247 if (isFromSystemMacro(S, CC))
3248 return;
3249
John McCallb4eb64d2010-10-08 02:01:28 +00003250 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003251 }
3252 return;
3253 }
3254
Ted Kremenekef9ff882011-03-10 20:03:42 +00003255 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003256 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003257 if (isFromSystemMacro(S, CC))
3258 return;
3259
Chandler Carrutha5b93322011-02-17 11:05:49 +00003260 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00003261 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3262 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003263 } else {
3264 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3265 }
3266 }
John McCall51313c32010-01-04 23:31:57 +00003267
3268 return;
3269 }
3270
John McCallf2370c92010-01-06 05:24:50 +00003271 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003272 return;
3273
Richard Trieu1838ca52011-05-29 19:59:02 +00003274 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3275 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3276 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3277 << E->getSourceRange() << clang::SourceRange(CC);
3278 return;
3279 }
3280
John McCall323ed742010-05-06 08:58:33 +00003281 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003282 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003283
3284 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003285 // If the source is a constant, use a default-on diagnostic.
3286 // TODO: this should happen for bitfield stores, too.
3287 llvm::APSInt Value(32);
3288 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003289 if (isFromSystemMacro(S, CC))
3290 return;
3291
John McCall091f23f2010-11-09 22:22:12 +00003292 std::string PrettySourceValue = Value.toString(10);
3293 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3294
3295 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3296 << PrettySourceValue << PrettyTargetValue
3297 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3298 return;
3299 }
3300
Chris Lattnerb792b302011-06-14 04:51:15 +00003301 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003302 if (isFromSystemMacro(S, CC))
3303 return;
3304
John McCallf2370c92010-01-06 05:24:50 +00003305 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003306 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3307 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003308 }
3309
3310 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3311 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3312 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003313
3314 if (isFromSystemMacro(S, CC))
3315 return;
3316
John McCall323ed742010-05-06 08:58:33 +00003317 unsigned DiagID = diag::warn_impcast_integer_sign;
3318
3319 // Traditionally, gcc has warned about this under -Wsign-compare.
3320 // We also want to warn about it in -Wconversion.
3321 // So if -Wconversion is off, use a completely identical diagnostic
3322 // in the sign-compare group.
3323 // The conditional-checking code will
3324 if (ICContext) {
3325 DiagID = diag::warn_impcast_integer_sign_conditional;
3326 *ICContext = true;
3327 }
3328
John McCallb4eb64d2010-10-08 02:01:28 +00003329 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003330 }
3331
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003332 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003333 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3334 // type, to give us better diagnostics.
3335 QualType SourceType = E->getType();
3336 if (!S.getLangOptions().CPlusPlus) {
3337 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3338 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3339 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3340 SourceType = S.Context.getTypeDeclType(Enum);
3341 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3342 }
3343 }
3344
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003345 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3346 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3347 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003348 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003349 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003350 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003351 SourceEnum != TargetEnum) {
3352 if (isFromSystemMacro(S, CC))
3353 return;
3354
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003355 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003356 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003357 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003358
John McCall51313c32010-01-04 23:31:57 +00003359 return;
3360}
3361
John McCall323ed742010-05-06 08:58:33 +00003362void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3363
3364void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003365 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003366 E = E->IgnoreParenImpCasts();
3367
3368 if (isa<ConditionalOperator>(E))
3369 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3370
John McCallb4eb64d2010-10-08 02:01:28 +00003371 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003372 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003373 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003374 return;
3375}
3376
3377void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003378 SourceLocation CC = E->getQuestionLoc();
3379
3380 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003381
3382 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003383 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3384 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003385
3386 // If -Wconversion would have warned about either of the candidates
3387 // for a signedness conversion to the context type...
3388 if (!Suspicious) return;
3389
3390 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003391 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3392 CC))
John McCall323ed742010-05-06 08:58:33 +00003393 return;
3394
John McCall323ed742010-05-06 08:58:33 +00003395 // ...then check whether it would have warned about either of the
3396 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003397 if (E->getType() == T) return;
3398
3399 Suspicious = false;
3400 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3401 E->getType(), CC, &Suspicious);
3402 if (!Suspicious)
3403 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003404 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003405}
3406
3407/// AnalyzeImplicitConversions - Find and report any interesting
3408/// implicit conversions in the given expression. There are a couple
3409/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003410void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003411 QualType T = OrigE->getType();
3412 Expr *E = OrigE->IgnoreParenImpCasts();
3413
3414 // For conditional operators, we analyze the arguments as if they
3415 // were being fed directly into the output.
3416 if (isa<ConditionalOperator>(E)) {
3417 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3418 CheckConditionalOperator(S, CO, T);
3419 return;
3420 }
3421
3422 // Go ahead and check any implicit conversions we might have skipped.
3423 // The non-canonical typecheck is just an optimization;
3424 // CheckImplicitConversion will filter out dead implicit conversions.
3425 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003426 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003427
3428 // Now continue drilling into this expression.
3429
3430 // Skip past explicit casts.
3431 if (isa<ExplicitCastExpr>(E)) {
3432 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003433 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003434 }
3435
John McCallbeb22aa2010-11-09 23:24:47 +00003436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3437 // Do a somewhat different check with comparison operators.
3438 if (BO->isComparisonOp())
3439 return AnalyzeComparison(S, BO);
3440
3441 // And with assignments and compound assignments.
3442 if (BO->isAssignmentOp())
3443 return AnalyzeAssignment(S, BO);
3444 }
John McCall323ed742010-05-06 08:58:33 +00003445
3446 // These break the otherwise-useful invariant below. Fortunately,
3447 // we don't really need to recurse into them, because any internal
3448 // expressions should have been analyzed already when they were
3449 // built into statements.
3450 if (isa<StmtExpr>(E)) return;
3451
3452 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003453 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003454
3455 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003456 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003457 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003458 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003459}
3460
3461} // end anonymous namespace
3462
3463/// Diagnoses "dangerous" implicit conversions within the given
3464/// expression (which is a full expression). Implements -Wconversion
3465/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003466///
3467/// \param CC the "context" location of the implicit conversion, i.e.
3468/// the most location of the syntactic entity requiring the implicit
3469/// conversion
3470void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003471 // Don't diagnose in unevaluated contexts.
3472 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3473 return;
3474
3475 // Don't diagnose for value- or type-dependent expressions.
3476 if (E->isTypeDependent() || E->isValueDependent())
3477 return;
3478
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003479 // Check for array bounds violations in cases where the check isn't triggered
3480 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3481 // ArraySubscriptExpr is on the RHS of a variable initialization.
3482 CheckArrayAccess(E);
3483
John McCallb4eb64d2010-10-08 02:01:28 +00003484 // This is not the right CC for (e.g.) a variable initialization.
3485 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003486}
3487
John McCall15d7d122010-11-11 03:21:53 +00003488void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3489 FieldDecl *BitField,
3490 Expr *Init) {
3491 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3492}
3493
Mike Stumpf8c49212010-01-21 03:59:47 +00003494/// CheckParmsForFunctionDef - Check that the parameters of the given
3495/// function are appropriate for the definition of a function. This
3496/// takes care of any checks that cannot be performed on the
3497/// declaration itself, e.g., that the types of each of the function
3498/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003499bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3500 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003501 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003502 for (; P != PEnd; ++P) {
3503 ParmVarDecl *Param = *P;
3504
Mike Stumpf8c49212010-01-21 03:59:47 +00003505 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3506 // function declarator that is part of a function definition of
3507 // that function shall not have incomplete type.
3508 //
3509 // This is also C++ [dcl.fct]p6.
3510 if (!Param->isInvalidDecl() &&
3511 RequireCompleteType(Param->getLocation(), Param->getType(),
3512 diag::err_typecheck_decl_incomplete_type)) {
3513 Param->setInvalidDecl();
3514 HasInvalidParm = true;
3515 }
3516
3517 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3518 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003519 if (CheckParameterNames &&
3520 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003521 !Param->isImplicit() &&
3522 !getLangOptions().CPlusPlus)
3523 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003524
3525 // C99 6.7.5.3p12:
3526 // If the function declarator is not part of a definition of that
3527 // function, parameters may have incomplete type and may use the [*]
3528 // notation in their sequences of declarator specifiers to specify
3529 // variable length array types.
3530 QualType PType = Param->getOriginalType();
3531 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3532 if (AT->getSizeModifier() == ArrayType::Star) {
3533 // FIXME: This diagnosic should point the the '[*]' if source-location
3534 // information is added for it.
3535 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3536 }
3537 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003538 }
3539
3540 return HasInvalidParm;
3541}
John McCallb7f4ffe2010-08-12 21:44:57 +00003542
3543/// CheckCastAlign - Implements -Wcast-align, which warns when a
3544/// pointer cast increases the alignment requirements.
3545void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3546 // This is actually a lot of work to potentially be doing on every
3547 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003548 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3549 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003550 == Diagnostic::Ignored)
3551 return;
3552
3553 // Ignore dependent types.
3554 if (T->isDependentType() || Op->getType()->isDependentType())
3555 return;
3556
3557 // Require that the destination be a pointer type.
3558 const PointerType *DestPtr = T->getAs<PointerType>();
3559 if (!DestPtr) return;
3560
3561 // If the destination has alignment 1, we're done.
3562 QualType DestPointee = DestPtr->getPointeeType();
3563 if (DestPointee->isIncompleteType()) return;
3564 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3565 if (DestAlign.isOne()) return;
3566
3567 // Require that the source be a pointer type.
3568 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3569 if (!SrcPtr) return;
3570 QualType SrcPointee = SrcPtr->getPointeeType();
3571
3572 // Whitelist casts from cv void*. We already implicitly
3573 // whitelisted casts to cv void*, since they have alignment 1.
3574 // Also whitelist casts involving incomplete types, which implicitly
3575 // includes 'void'.
3576 if (SrcPointee->isIncompleteType()) return;
3577
3578 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3579 if (SrcAlign >= DestAlign) return;
3580
3581 Diag(TRange.getBegin(), diag::warn_cast_align)
3582 << Op->getType() << T
3583 << static_cast<unsigned>(SrcAlign.getQuantity())
3584 << static_cast<unsigned>(DestAlign.getQuantity())
3585 << TRange << Op->getSourceRange();
3586}
3587
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003588static const Type* getElementType(const Expr *BaseExpr) {
3589 const Type* EltType = BaseExpr->getType().getTypePtr();
3590 if (EltType->isAnyPointerType())
3591 return EltType->getPointeeType().getTypePtr();
3592 else if (EltType->isArrayType())
3593 return EltType->getBaseElementTypeUnsafe();
3594 return EltType;
3595}
3596
Chandler Carruthc2684342011-08-05 09:10:50 +00003597/// \brief Check whether this array fits the idiom of a size-one tail padded
3598/// array member of a struct.
3599///
3600/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3601/// commonly used to emulate flexible arrays in C89 code.
3602static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3603 const NamedDecl *ND) {
3604 if (Size != 1 || !ND) return false;
3605
3606 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3607 if (!FD) return false;
3608
3609 // Don't consider sizes resulting from macro expansions or template argument
3610 // substitution to form C89 tail-padded arrays.
3611 ConstantArrayTypeLoc TL =
3612 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3613 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3614 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3615 return false;
3616
3617 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3618 if (!RD || !RD->isStruct())
3619 return false;
3620
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003621 // See if this is the last field decl in the record.
3622 const Decl *D = FD;
3623 while ((D = D->getNextDeclInContext()))
3624 if (isa<FieldDecl>(D))
3625 return false;
3626 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003627}
3628
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003629void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3630 bool isSubscript, bool AllowOnePastEnd) {
3631 const Type* EffectiveType = getElementType(BaseExpr);
3632 BaseExpr = BaseExpr->IgnoreParenCasts();
3633 IndexExpr = IndexExpr->IgnoreParenCasts();
3634
Chandler Carruth34064582011-02-17 20:55:08 +00003635 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003636 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003637 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003638 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003639
Chandler Carruth34064582011-02-17 20:55:08 +00003640 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003641 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003642 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003643 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003644 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003645
Chandler Carruthba447122011-08-05 08:07:29 +00003646 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003647 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3648 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003649 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003650 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003651
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003652 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003653 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003654 if (!size.isStrictlyPositive())
3655 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003656
3657 const Type* BaseType = getElementType(BaseExpr);
3658 if (!isSubscript && BaseType != EffectiveType) {
3659 // Make sure we're comparing apples to apples when comparing index to size
3660 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3661 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003662 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003663 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003664 if (ptrarith_typesize != array_typesize) {
3665 // There's a cast to a different size type involved
3666 uint64_t ratio = array_typesize / ptrarith_typesize;
3667 // TODO: Be smarter about handling cases where array_typesize is not a
3668 // multiple of ptrarith_typesize
3669 if (ptrarith_typesize * ratio == array_typesize)
3670 size *= llvm::APInt(size.getBitWidth(), ratio);
3671 }
3672 }
3673
Chandler Carruth34064582011-02-17 20:55:08 +00003674 if (size.getBitWidth() > index.getBitWidth())
3675 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003676 else if (size.getBitWidth() < index.getBitWidth())
3677 size = size.sext(index.getBitWidth());
3678
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003679 // For array subscripting the index must be less than size, but for pointer
3680 // arithmetic also allow the index (offset) to be equal to size since
3681 // computing the next address after the end of the array is legal and
3682 // commonly done e.g. in C++ iterators and range-based for loops.
3683 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003684 return;
3685
3686 // Also don't warn for arrays of size 1 which are members of some
3687 // structure. These are often used to approximate flexible arrays in C89
3688 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003689 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003690 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003691
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003692 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3693 if (isSubscript)
3694 DiagID = diag::warn_array_index_exceeds_bounds;
3695
3696 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3697 PDiag(DiagID) << index.toString(10, true)
3698 << size.toString(10, true)
3699 << (unsigned)size.getLimitedValue(~0U)
3700 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003701 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003702 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3703 if (!isSubscript) {
3704 DiagID = diag::warn_ptr_arith_precedes_bounds;
3705 if (index.isNegative()) index = -index;
3706 }
3707
3708 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3709 PDiag(DiagID) << index.toString(10, true)
3710 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003711 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003712
Chandler Carruth35001ca2011-02-17 21:10:52 +00003713 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003714 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3715 PDiag(diag::note_array_index_out_of_bounds)
3716 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003717}
3718
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003719void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003720 int AllowOnePastEnd = 0;
3721 while (expr) {
3722 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003723 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003724 case Stmt::ArraySubscriptExprClass: {
3725 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3726 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3727 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003728 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003729 }
3730 case Stmt::UnaryOperatorClass: {
3731 // Only unwrap the * and & unary operators
3732 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3733 expr = UO->getSubExpr();
3734 switch (UO->getOpcode()) {
3735 case UO_AddrOf:
3736 AllowOnePastEnd++;
3737 break;
3738 case UO_Deref:
3739 AllowOnePastEnd--;
3740 break;
3741 default:
3742 return;
3743 }
3744 break;
3745 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003746 case Stmt::ConditionalOperatorClass: {
3747 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3748 if (const Expr *lhs = cond->getLHS())
3749 CheckArrayAccess(lhs);
3750 if (const Expr *rhs = cond->getRHS())
3751 CheckArrayAccess(rhs);
3752 return;
3753 }
3754 default:
3755 return;
3756 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003757 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003758}
John McCallf85e1932011-06-15 23:02:42 +00003759
3760//===--- CHECK: Objective-C retain cycles ----------------------------------//
3761
3762namespace {
3763 struct RetainCycleOwner {
3764 RetainCycleOwner() : Variable(0), Indirect(false) {}
3765 VarDecl *Variable;
3766 SourceRange Range;
3767 SourceLocation Loc;
3768 bool Indirect;
3769
3770 void setLocsFrom(Expr *e) {
3771 Loc = e->getExprLoc();
3772 Range = e->getSourceRange();
3773 }
3774 };
3775}
3776
3777/// Consider whether capturing the given variable can possibly lead to
3778/// a retain cycle.
3779static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3780 // In ARC, it's captured strongly iff the variable has __strong
3781 // lifetime. In MRR, it's captured strongly if the variable is
3782 // __block and has an appropriate type.
3783 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3784 return false;
3785
3786 owner.Variable = var;
3787 owner.setLocsFrom(ref);
3788 return true;
3789}
3790
3791static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3792 while (true) {
3793 e = e->IgnoreParens();
3794 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3795 switch (cast->getCastKind()) {
3796 case CK_BitCast:
3797 case CK_LValueBitCast:
3798 case CK_LValueToRValue:
John McCall7e5e5f42011-07-07 06:58:02 +00003799 case CK_ObjCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00003800 e = cast->getSubExpr();
3801 continue;
3802
3803 case CK_GetObjCProperty: {
3804 // Bail out if this isn't a strong explicit property.
3805 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3806 if (pre->isImplicitProperty()) return false;
3807 ObjCPropertyDecl *property = pre->getExplicitProperty();
3808 if (!(property->getPropertyAttributes() &
3809 (ObjCPropertyDecl::OBJC_PR_retain |
3810 ObjCPropertyDecl::OBJC_PR_copy |
3811 ObjCPropertyDecl::OBJC_PR_strong)) &&
3812 !(property->getPropertyIvarDecl() &&
3813 property->getPropertyIvarDecl()->getType()
3814 .getObjCLifetime() == Qualifiers::OCL_Strong))
3815 return false;
3816
3817 owner.Indirect = true;
3818 e = const_cast<Expr*>(pre->getBase());
3819 continue;
3820 }
3821
3822 default:
3823 return false;
3824 }
3825 }
3826
3827 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3828 ObjCIvarDecl *ivar = ref->getDecl();
3829 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3830 return false;
3831
3832 // Try to find a retain cycle in the base.
3833 if (!findRetainCycleOwner(ref->getBase(), owner))
3834 return false;
3835
3836 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3837 owner.Indirect = true;
3838 return true;
3839 }
3840
3841 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3842 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3843 if (!var) return false;
3844 return considerVariable(var, ref, owner);
3845 }
3846
3847 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3848 owner.Variable = ref->getDecl();
3849 owner.setLocsFrom(ref);
3850 return true;
3851 }
3852
3853 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3854 if (member->isArrow()) return false;
3855
3856 // Don't count this as an indirect ownership.
3857 e = member->getBase();
3858 continue;
3859 }
3860
3861 // Array ivars?
3862
3863 return false;
3864 }
3865}
3866
3867namespace {
3868 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3869 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3870 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3871 Variable(variable), Capturer(0) {}
3872
3873 VarDecl *Variable;
3874 Expr *Capturer;
3875
3876 void VisitDeclRefExpr(DeclRefExpr *ref) {
3877 if (ref->getDecl() == Variable && !Capturer)
3878 Capturer = ref;
3879 }
3880
3881 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3882 if (ref->getDecl() == Variable && !Capturer)
3883 Capturer = ref;
3884 }
3885
3886 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3887 if (Capturer) return;
3888 Visit(ref->getBase());
3889 if (Capturer && ref->isFreeIvar())
3890 Capturer = ref;
3891 }
3892
3893 void VisitBlockExpr(BlockExpr *block) {
3894 // Look inside nested blocks
3895 if (block->getBlockDecl()->capturesVariable(Variable))
3896 Visit(block->getBlockDecl()->getBody());
3897 }
3898 };
3899}
3900
3901/// Check whether the given argument is a block which captures a
3902/// variable.
3903static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3904 assert(owner.Variable && owner.Loc.isValid());
3905
3906 e = e->IgnoreParenCasts();
3907 BlockExpr *block = dyn_cast<BlockExpr>(e);
3908 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3909 return 0;
3910
3911 FindCaptureVisitor visitor(S.Context, owner.Variable);
3912 visitor.Visit(block->getBlockDecl()->getBody());
3913 return visitor.Capturer;
3914}
3915
3916static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3917 RetainCycleOwner &owner) {
3918 assert(capturer);
3919 assert(owner.Variable && owner.Loc.isValid());
3920
3921 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3922 << owner.Variable << capturer->getSourceRange();
3923 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3924 << owner.Indirect << owner.Range;
3925}
3926
3927/// Check for a keyword selector that starts with the word 'add' or
3928/// 'set'.
3929static bool isSetterLikeSelector(Selector sel) {
3930 if (sel.isUnarySelector()) return false;
3931
Chris Lattner5f9e2722011-07-23 10:55:15 +00003932 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00003933 while (!str.empty() && str.front() == '_') str = str.substr(1);
3934 if (str.startswith("set") || str.startswith("add"))
3935 str = str.substr(3);
3936 else
3937 return false;
3938
3939 if (str.empty()) return true;
3940 return !islower(str.front());
3941}
3942
3943/// Check a message send to see if it's likely to cause a retain cycle.
3944void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3945 // Only check instance methods whose selector looks like a setter.
3946 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3947 return;
3948
3949 // Try to find a variable that the receiver is strongly owned by.
3950 RetainCycleOwner owner;
3951 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3952 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3953 return;
3954 } else {
3955 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3956 owner.Variable = getCurMethodDecl()->getSelfDecl();
3957 owner.Loc = msg->getSuperLoc();
3958 owner.Range = msg->getSuperLoc();
3959 }
3960
3961 // Check whether the receiver is captured by any of the arguments.
3962 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
3963 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
3964 return diagnoseRetainCycle(*this, capturer, owner);
3965}
3966
3967/// Check a property assign to see if it's likely to cause a retain cycle.
3968void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
3969 RetainCycleOwner owner;
3970 if (!findRetainCycleOwner(receiver, owner))
3971 return;
3972
3973 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
3974 diagnoseRetainCycle(*this, capturer, owner);
3975}
3976
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003977bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00003978 QualType LHS, Expr *RHS) {
3979 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
3980 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003981 return false;
3982 // strip off any implicit cast added to get to the one arc-specific
3983 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
3984 if (cast->getCastKind() == CK_ObjCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00003985 Diag(Loc, diag::warn_arc_retained_assign)
3986 << (LT == Qualifiers::OCL_ExplicitNone)
3987 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003988 return true;
3989 }
3990 RHS = cast->getSubExpr();
3991 }
3992 return false;
John McCallf85e1932011-06-15 23:02:42 +00003993}
3994
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003995void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
3996 Expr *LHS, Expr *RHS) {
3997 QualType LHSType = LHS->getType();
3998 if (checkUnsafeAssigns(Loc, LHSType, RHS))
3999 return;
4000 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4001 // FIXME. Check for other life times.
4002 if (LT != Qualifiers::OCL_None)
4003 return;
4004
4005 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4006 if (PRE->isImplicitProperty())
4007 return;
4008 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4009 if (!PD)
4010 return;
4011
4012 unsigned Attributes = PD->getPropertyAttributes();
4013 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4014 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4015 if (cast->getCastKind() == CK_ObjCConsumeObject) {
4016 Diag(Loc, diag::warn_arc_retained_property_assign)
4017 << RHS->getSourceRange();
4018 return;
4019 }
4020 RHS = cast->getSubExpr();
4021 }
4022 }
4023}