blob: 68e25e7f4e5a48e218fac37c74c0ff58cdb7656b [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
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000019#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000021#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000024#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000025#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "clang/AST/DeclObjC.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000030#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000033#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000034#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000035#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000036#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000037#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000038using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000039using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000040
Chris Lattner60800082009-02-18 17:49:48 +000041SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
42 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000043 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
44 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000045}
Chris Lattner08f92e32010-11-17 07:37:15 +000046
Chris Lattner60800082009-02-18 17:49:48 +000047
Ryan Flynn4403a5e2009-08-06 03:00:50 +000048/// CheckablePrintfAttr - does a function call have a "printf" attribute
49/// and arguments that merit checking?
50bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
51 if (Format->getType() == "printf") return true;
52 if (Format->getType() == "printf0") {
53 // printf0 allows null "format" string; if so don't check format/args
54 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000055 // Does the index refer to the implicit object argument?
56 if (isa<CXXMemberCallExpr>(TheCall)) {
57 if (format_idx == 0)
58 return false;
59 --format_idx;
60 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000061 if (format_idx < TheCall->getNumArgs()) {
62 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000063 if (!Format->isNullPointerConstant(Context,
64 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000065 return true;
66 }
67 }
68 return false;
69}
Chris Lattner60800082009-02-18 17:49:48 +000070
John McCall8e10f3b2011-02-26 05:39:39 +000071/// Checks that a call expression's argument count is the desired number.
72/// This is useful when doing custom type-checking. Returns true on error.
73static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
74 unsigned argCount = call->getNumArgs();
75 if (argCount == desiredArgCount) return false;
76
77 if (argCount < desiredArgCount)
78 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
79 << 0 /*function call*/ << desiredArgCount << argCount
80 << call->getSourceRange();
81
82 // Highlight all the excess arguments.
83 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
84 call->getArg(argCount - 1)->getLocEnd());
85
86 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
87 << 0 /*function call*/ << desiredArgCount << argCount
88 << call->getArg(1)->getSourceRange();
89}
90
John McCall60d7b3a2010-08-24 06:29:42 +000091ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000092Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000093 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000094
Chris Lattner946928f2010-10-01 23:23:24 +000095 // Find out if any arguments are required to be integer constant expressions.
96 unsigned ICEArguments = 0;
97 ASTContext::GetBuiltinTypeError Error;
98 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
99 if (Error != ASTContext::GE_None)
100 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
101
102 // If any arguments are required to be ICE's, check and diagnose.
103 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
104 // Skip arguments not required to be ICE's.
105 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
106
107 llvm::APSInt Result;
108 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
109 return true;
110 ICEArguments &= ~(1 << ArgNo);
111 }
112
Anders Carlssond406bf02009-08-16 01:56:34 +0000113 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000114 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000115 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000117 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000119 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000120 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinVAStart(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000125 case Builtin::BI__builtin_isgreater:
126 case Builtin::BI__builtin_isgreaterequal:
127 case Builtin::BI__builtin_isless:
128 case Builtin::BI__builtin_islessequal:
129 case Builtin::BI__builtin_islessgreater:
130 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinUnorderedCompare(TheCall))
132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000134 case Builtin::BI__builtin_fpclassify:
135 if (SemaBuiltinFPClassification(TheCall, 6))
136 return ExprError();
137 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000138 case Builtin::BI__builtin_isfinite:
139 case Builtin::BI__builtin_isinf:
140 case Builtin::BI__builtin_isinf_sign:
141 case Builtin::BI__builtin_isnan:
142 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000143 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000144 return ExprError();
145 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000146 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000147 return SemaBuiltinShuffleVector(TheCall);
148 // TheCall will be freed by the smart pointer here, but that's fine, since
149 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000150 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000151 if (SemaBuiltinPrefetch(TheCall))
152 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000153 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000154 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 if (SemaBuiltinObjectSize(TheCall))
156 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000157 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000158 case Builtin::BI__builtin_longjmp:
159 if (SemaBuiltinLongjmp(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000162
163 case Builtin::BI__builtin_classify_type:
164 if (checkArgCount(*this, TheCall, 1)) return true;
165 TheCall->setType(Context.IntTy);
166 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000167 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000168 if (checkArgCount(*this, TheCall, 1)) return true;
169 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000170 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000171 case Builtin::BI__sync_fetch_and_add:
172 case Builtin::BI__sync_fetch_and_sub:
173 case Builtin::BI__sync_fetch_and_or:
174 case Builtin::BI__sync_fetch_and_and:
175 case Builtin::BI__sync_fetch_and_xor:
176 case Builtin::BI__sync_add_and_fetch:
177 case Builtin::BI__sync_sub_and_fetch:
178 case Builtin::BI__sync_and_and_fetch:
179 case Builtin::BI__sync_or_and_fetch:
180 case Builtin::BI__sync_xor_and_fetch:
181 case Builtin::BI__sync_val_compare_and_swap:
182 case Builtin::BI__sync_bool_compare_and_swap:
183 case Builtin::BI__sync_lock_test_and_set:
184 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000185 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000186 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000187 }
188
189 // Since the target specific builtins for each arch overlap, only check those
190 // of the arch we are compiling for.
191 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000192 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000193 case llvm::Triple::arm:
194 case llvm::Triple::thumb:
195 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
196 return ExprError();
197 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000198 default:
199 break;
200 }
201 }
202
203 return move(TheCallResult);
204}
205
Nate Begeman61eecf52010-06-14 05:21:25 +0000206// Get the valid immediate range for the specified NEON type code.
207static unsigned RFT(unsigned t, bool shift = false) {
208 bool quad = t & 0x10;
209
210 switch (t & 0x7) {
211 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000212 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000213 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000214 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000216 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000218 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000219 case 4: // f32
220 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000221 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000222 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000223 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000224 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000225 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000226 case 7: // float16
227 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000228 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000229 }
230 return 0;
231}
232
Nate Begeman26a31422010-06-08 02:47:44 +0000233bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000234 llvm::APSInt Result;
235
Nate Begeman0d15c532010-06-13 04:47:52 +0000236 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000237 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000238 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000239#define GET_NEON_OVERLOAD_CHECK
240#include "clang/Basic/arm_neon.inc"
241#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000242 }
243
Nate Begeman0d15c532010-06-13 04:47:52 +0000244 // For NEON intrinsics which are overloaded on vector element type, validate
245 // the immediate which specifies which variant to emit.
246 if (mask) {
247 unsigned ArgNo = TheCall->getNumArgs()-1;
248 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
249 return true;
250
Nate Begeman61eecf52010-06-14 05:21:25 +0000251 TV = Result.getLimitedValue(32);
252 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000253 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
254 << TheCall->getArg(ArgNo)->getSourceRange();
255 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000256
Nate Begeman0d15c532010-06-13 04:47:52 +0000257 // For NEON intrinsics which take an immediate value as part of the
258 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000259 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000260 switch (BuiltinID) {
261 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000262 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
263 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000264 case ARM::BI__builtin_arm_vcvtr_f:
265 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000266#define GET_NEON_IMMEDIATE_CHECK
267#include "clang/Basic/arm_neon.inc"
268#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000269 };
270
Nate Begeman61eecf52010-06-14 05:21:25 +0000271 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000272 if (SemaBuiltinConstantArg(TheCall, i, Result))
273 return true;
274
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000277 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000278 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000279 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000280
Nate Begeman99c40bb2010-08-03 21:32:34 +0000281 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000282 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000283}
Daniel Dunbarde454282008-10-02 18:44:07 +0000284
Anders Carlssond406bf02009-08-16 01:56:34 +0000285/// CheckFunctionCall - Check a direct function call for various correctness
286/// and safety properties not strictly enforced by the C type system.
287bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
288 // Get the IdentifierInfo* for the called function.
289 IdentifierInfo *FnInfo = FDecl->getIdentifier();
290
291 // None of the checks below are needed for functions that don't have
292 // simple names (e.g., C++ conversion functions).
293 if (!FnInfo)
294 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Daniel Dunbarde454282008-10-02 18:44:07 +0000296 // FIXME: This mechanism should be abstracted to be less fragile and
297 // more efficient. For example, just map function ids to custom
298 // handlers.
299
Ted Kremenekc82faca2010-09-09 04:33:05 +0000300 // Printf and scanf checking.
301 for (specific_attr_iterator<FormatAttr>
302 i = FDecl->specific_attr_begin<FormatAttr>(),
303 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
304
305 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000306 const bool b = Format->getType() == "scanf";
307 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000308 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000309 CheckPrintfScanfArguments(TheCall, HasVAListArg,
310 Format->getFormatIdx() - 1,
311 HasVAListArg ? 0 : Format->getFirstArg() - 1,
312 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000313 }
Chris Lattner59907c42007-08-10 20:18:51 +0000314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Ted Kremenekc82faca2010-09-09 04:33:05 +0000316 for (specific_attr_iterator<NonNullAttr>
317 i = FDecl->specific_attr_begin<NonNullAttr>(),
318 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000319 CheckNonNullArguments(*i, TheCall->getArgs(),
320 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000321 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000322
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000323 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000324 int CMF = -1;
325 switch (FDecl->getBuiltinID()) {
326 case Builtin::BI__builtin_memset:
327 case Builtin::BI__builtin___memset_chk:
328 case Builtin::BImemset:
329 CMF = CMF_Memset;
330 break;
331
332 case Builtin::BI__builtin_memcpy:
333 case Builtin::BI__builtin___memcpy_chk:
334 case Builtin::BImemcpy:
335 CMF = CMF_Memcpy;
336 break;
337
338 case Builtin::BI__builtin_memmove:
339 case Builtin::BI__builtin___memmove_chk:
340 case Builtin::BImemmove:
341 CMF = CMF_Memmove;
342 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000343
344 case Builtin::BIstrlcpy:
345 case Builtin::BIstrlcat:
346 CheckStrlcpycatArguments(TheCall, FnInfo);
347 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000348
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000349 case Builtin::BI__builtin_memcmp:
350 CMF = CMF_Memcmp;
351 break;
352
Douglas Gregor707a23e2011-06-16 17:56:04 +0000353 default:
354 if (FDecl->getLinkage() == ExternalLinkage &&
355 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
356 if (FnInfo->isStr("memset"))
357 CMF = CMF_Memset;
358 else if (FnInfo->isStr("memcpy"))
359 CMF = CMF_Memcpy;
360 else if (FnInfo->isStr("memmove"))
361 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000362 else if (FnInfo->isStr("memcmp"))
363 CMF = CMF_Memcmp;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000364 }
365 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000366 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000367
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000368 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000369 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000370 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000371
Anders Carlssond406bf02009-08-16 01:56:34 +0000372 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000373}
374
Anders Carlssond406bf02009-08-16 01:56:34 +0000375bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000376 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000377 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000378 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000381 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
382 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000383 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000385 QualType Ty = V->getType();
386 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000387 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek826a3452010-07-16 02:11:22 +0000389 const bool b = Format->getType() == "scanf";
390 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Anders Carlssond406bf02009-08-16 01:56:34 +0000393 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000394 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
395 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000396
397 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000398}
399
John McCall5f8d6042011-08-27 01:09:30 +0000400/// checkBuiltinArgument - Given a call to a builtin function, perform
401/// normal type-checking on the given argument, updating the call in
402/// place. This is useful when a builtin function requires custom
403/// type-checking for some of its arguments but not necessarily all of
404/// them.
405///
406/// Returns true on error.
407static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
408 FunctionDecl *Fn = E->getDirectCallee();
409 assert(Fn && "builtin call without direct callee!");
410
411 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
412 InitializedEntity Entity =
413 InitializedEntity::InitializeParameter(S.Context, Param);
414
415 ExprResult Arg = E->getArg(0);
416 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
417 if (Arg.isInvalid())
418 return true;
419
420 E->setArg(ArgIndex, Arg.take());
421 return false;
422}
423
Chris Lattner5caa3702009-05-08 06:58:22 +0000424/// SemaBuiltinAtomicOverloaded - We have a call to a function like
425/// __sync_fetch_and_add, which is an overloaded function based on the pointer
426/// type of its first argument. The main ActOnCallExpr routines have already
427/// promoted the types of arguments because all of these calls are prototyped as
428/// void(...).
429///
430/// This function goes through and does final semantic checking for these
431/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000432ExprResult
433Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000434 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000435 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
436 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
437
438 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000439 if (TheCall->getNumArgs() < 1) {
440 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
441 << 0 << 1 << TheCall->getNumArgs()
442 << TheCall->getCallee()->getSourceRange();
443 return ExprError();
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner5caa3702009-05-08 06:58:22 +0000446 // Inspect the first argument of the atomic builtin. This should always be
447 // a pointer type, whose element is an integral scalar or pointer type.
448 // Because it is a pointer type, we don't have to worry about any implicit
449 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000450 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000451 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000452 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
453 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000454 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
455 << FirstArg->getType() << FirstArg->getSourceRange();
456 return ExprError();
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
John McCallf85e1932011-06-15 23:02:42 +0000459 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000460 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000461 !ValType->isBlockPointerType()) {
462 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
463 << FirstArg->getType() << FirstArg->getSourceRange();
464 return ExprError();
465 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000466
John McCallf85e1932011-06-15 23:02:42 +0000467 switch (ValType.getObjCLifetime()) {
468 case Qualifiers::OCL_None:
469 case Qualifiers::OCL_ExplicitNone:
470 // okay
471 break;
472
473 case Qualifiers::OCL_Weak:
474 case Qualifiers::OCL_Strong:
475 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000476 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000477 << ValType << FirstArg->getSourceRange();
478 return ExprError();
479 }
480
Chandler Carruth8d13d222010-07-18 20:54:12 +0000481 // The majority of builtins return a value, but a few have special return
482 // types, so allow them to override appropriately below.
483 QualType ResultType = ValType;
484
Chris Lattner5caa3702009-05-08 06:58:22 +0000485 // We need to figure out which concrete builtin this maps onto. For example,
486 // __sync_fetch_and_add with a 2 byte object turns into
487 // __sync_fetch_and_add_2.
488#define BUILTIN_ROW(x) \
489 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
490 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Chris Lattner5caa3702009-05-08 06:58:22 +0000492 static const unsigned BuiltinIndices[][5] = {
493 BUILTIN_ROW(__sync_fetch_and_add),
494 BUILTIN_ROW(__sync_fetch_and_sub),
495 BUILTIN_ROW(__sync_fetch_and_or),
496 BUILTIN_ROW(__sync_fetch_and_and),
497 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner5caa3702009-05-08 06:58:22 +0000499 BUILTIN_ROW(__sync_add_and_fetch),
500 BUILTIN_ROW(__sync_sub_and_fetch),
501 BUILTIN_ROW(__sync_and_and_fetch),
502 BUILTIN_ROW(__sync_or_and_fetch),
503 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner5caa3702009-05-08 06:58:22 +0000505 BUILTIN_ROW(__sync_val_compare_and_swap),
506 BUILTIN_ROW(__sync_bool_compare_and_swap),
507 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000508 BUILTIN_ROW(__sync_lock_release),
509 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000510 };
Mike Stump1eb44332009-09-09 15:08:12 +0000511#undef BUILTIN_ROW
512
Chris Lattner5caa3702009-05-08 06:58:22 +0000513 // Determine the index of the size.
514 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000515 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000516 case 1: SizeIndex = 0; break;
517 case 2: SizeIndex = 1; break;
518 case 4: SizeIndex = 2; break;
519 case 8: SizeIndex = 3; break;
520 case 16: SizeIndex = 4; break;
521 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000522 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
523 << FirstArg->getType() << FirstArg->getSourceRange();
524 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner5caa3702009-05-08 06:58:22 +0000527 // Each of these builtins has one pointer argument, followed by some number of
528 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
529 // that we ignore. Find out which row of BuiltinIndices to read from as well
530 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000531 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000532 unsigned BuiltinIndex, NumFixed = 1;
533 switch (BuiltinID) {
534 default: assert(0 && "Unknown overloaded atomic builtin!");
535 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
536 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
537 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
538 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
539 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000541 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
542 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
543 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
544 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
545 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattner5caa3702009-05-08 06:58:22 +0000547 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000548 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000549 NumFixed = 2;
550 break;
551 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000552 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000553 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000554 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000556 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000557 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000558 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000559 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000560 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000561 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000562 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000563 }
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner5caa3702009-05-08 06:58:22 +0000565 // Now that we know how many fixed arguments we expect, first check that we
566 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000567 if (TheCall->getNumArgs() < 1+NumFixed) {
568 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
569 << 0 << 1+NumFixed << TheCall->getNumArgs()
570 << TheCall->getCallee()->getSourceRange();
571 return ExprError();
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000574 // Get the decl for the concrete builtin from this, we can tell what the
575 // concrete integer type we should convert to is.
576 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
577 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
578 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000579 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000580 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
581 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000582
John McCallf871d0c2010-08-07 06:22:56 +0000583 // The first argument --- the pointer --- has a fixed type; we
584 // deduce the types of the rest of the arguments accordingly. Walk
585 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000586 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000587 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattner5caa3702009-05-08 06:58:22 +0000589 // If the argument is an implicit cast, then there was a promotion due to
590 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000591 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000592 Arg = ICE->getSubExpr();
593 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000594 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattner5caa3702009-05-08 06:58:22 +0000597 // GCC does an implicit conversion to the pointer or integer ValType. This
598 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000599 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000600 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000601 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000602 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
603 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000604 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000605 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Chris Lattner5caa3702009-05-08 06:58:22 +0000607 // Okay, we have something that *can* be converted to the right type. Check
608 // to see if there is a potentially weird extension going on here. This can
609 // happen when you do an atomic operation on something like an char* and
610 // pass in 42. The 42 gets converted to char. This is even more strange
611 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000612 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000613 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
614 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000615 }
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000617 ASTContext& Context = this->getASTContext();
618
619 // Create a new DeclRefExpr to refer to the new decl.
620 DeclRefExpr* NewDRE = DeclRefExpr::Create(
621 Context,
622 DRE->getQualifierLoc(),
623 NewBuiltinDecl,
624 DRE->getLocation(),
625 NewBuiltinDecl->getType(),
626 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattner5caa3702009-05-08 06:58:22 +0000628 // Set the callee in the CallExpr.
629 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000630 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000631 if (PromotedCall.isInvalid())
632 return ExprError();
633 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000635 // Change the result type of the call to match the original value type. This
636 // is arbitrary, but the codegen for these builtins ins design to handle it
637 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000638 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000639
640 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000641}
642
643
Chris Lattner69039812009-02-18 06:01:06 +0000644/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000645/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000646/// Note: It might also make sense to do the UTF-16 conversion here (would
647/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000648bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000649 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000650 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
651
Douglas Gregor5cee1192011-07-27 05:40:30 +0000652 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000653 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
654 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000655 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000658 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000659 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000660 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000661 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000662 const UTF8 *FromPtr = (UTF8 *)String.data();
663 UTF16 *ToPtr = &ToBuf[0];
664
665 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
666 &ToPtr, ToPtr + NumBytes,
667 strictConversion);
668 // Check for conversion failure.
669 if (Result != conversionOK)
670 Diag(Arg->getLocStart(),
671 diag::warn_cfstring_truncated) << Arg->getSourceRange();
672 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000673 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000674}
675
Chris Lattnerc27c6652007-12-20 00:05:45 +0000676/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
677/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000678bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
679 Expr *Fn = TheCall->getCallee();
680 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000681 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000682 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000683 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
684 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000685 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000687 return true;
688 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000689
690 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000691 return Diag(TheCall->getLocEnd(),
692 diag::err_typecheck_call_too_few_args_at_least)
693 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000694 }
695
John McCall5f8d6042011-08-27 01:09:30 +0000696 // Type-check the first argument normally.
697 if (checkBuiltinArgument(*this, TheCall, 0))
698 return true;
699
Chris Lattnerc27c6652007-12-20 00:05:45 +0000700 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000701 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000702 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000703 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000704 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000705 else if (FunctionDecl *FD = getCurFunctionDecl())
706 isVariadic = FD->isVariadic();
707 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000708 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerc27c6652007-12-20 00:05:45 +0000710 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000711 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
712 return true;
713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattner30ce3442007-12-19 23:59:04 +0000715 // Verify that the second argument to the builtin is the last argument of the
716 // current function or method.
717 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000718 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Anders Carlsson88cf2262008-02-11 04:20:54 +0000720 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
721 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000722 // FIXME: This isn't correct for methods (results in bogus warning).
723 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000724 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000725 if (CurBlock)
726 LastArg = *(CurBlock->TheDecl->param_end()-1);
727 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000728 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000729 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000730 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000731 SecondArgIsLastNamedArgument = PV == LastArg;
732 }
733 }
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattner30ce3442007-12-19 23:59:04 +0000735 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000736 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000737 diag::warn_second_parameter_of_va_start_not_last_named_argument);
738 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000739}
Chris Lattner30ce3442007-12-19 23:59:04 +0000740
Chris Lattner1b9a0792007-12-20 00:26:33 +0000741/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
742/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000743bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
744 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000745 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000746 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000747 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000748 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000750 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000751 << SourceRange(TheCall->getArg(2)->getLocStart(),
752 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000753
John Wiegley429bb272011-04-08 18:41:53 +0000754 ExprResult OrigArg0 = TheCall->getArg(0);
755 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000756
Chris Lattner1b9a0792007-12-20 00:26:33 +0000757 // Do standard promotions between the two arguments, returning their common
758 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000759 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000760 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
761 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000762
763 // Make sure any conversions are pushed back into the call; this is
764 // type safe since unordered compare builtins are declared as "_Bool
765 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000766 TheCall->setArg(0, OrigArg0.get());
767 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000768
John Wiegley429bb272011-04-08 18:41:53 +0000769 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000770 return false;
771
Chris Lattner1b9a0792007-12-20 00:26:33 +0000772 // If the common type isn't a real floating type, then the arguments were
773 // invalid for this operation.
774 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000775 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000776 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000777 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
778 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattner1b9a0792007-12-20 00:26:33 +0000780 return false;
781}
782
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000783/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
784/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000785/// to check everything. We expect the last argument to be a floating point
786/// value.
787bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
788 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000789 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000790 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000791 if (TheCall->getNumArgs() > NumArgs)
792 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000793 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000794 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000795 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000796 (*(TheCall->arg_end()-1))->getLocEnd());
797
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000798 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Eli Friedman9ac6f622009-08-31 20:06:00 +0000800 if (OrigArg->isTypeDependent())
801 return false;
802
Chris Lattner81368fb2010-05-06 05:50:07 +0000803 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000804 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000805 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000806 diag::err_typecheck_call_invalid_unary_fp)
807 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner81368fb2010-05-06 05:50:07 +0000809 // If this is an implicit conversion from float -> double, remove it.
810 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
811 Expr *CastArg = Cast->getSubExpr();
812 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
813 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
814 "promotion from float to double is the only expected cast here");
815 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000816 TheCall->setArg(NumArgs-1, CastArg);
817 OrigArg = CastArg;
818 }
819 }
820
Eli Friedman9ac6f622009-08-31 20:06:00 +0000821 return false;
822}
823
Eli Friedmand38617c2008-05-14 19:38:39 +0000824/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
825// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000826ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000827 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000828 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000829 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000830 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000831 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000832
Nate Begeman37b6a572010-06-08 00:16:34 +0000833 // Determine which of the following types of shufflevector we're checking:
834 // 1) unary, vector mask: (lhs, mask)
835 // 2) binary, vector mask: (lhs, rhs, mask)
836 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
837 QualType resType = TheCall->getArg(0)->getType();
838 unsigned numElements = 0;
839
Douglas Gregorcde01732009-05-19 22:10:17 +0000840 if (!TheCall->getArg(0)->isTypeDependent() &&
841 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000842 QualType LHSType = TheCall->getArg(0)->getType();
843 QualType RHSType = TheCall->getArg(1)->getType();
844
845 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000846 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000847 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000848 TheCall->getArg(1)->getLocEnd());
849 return ExprError();
850 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000851
852 numElements = LHSType->getAs<VectorType>()->getNumElements();
853 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Nate Begeman37b6a572010-06-08 00:16:34 +0000855 // Check to see if we have a call with 2 vector arguments, the unary shuffle
856 // with mask. If so, verify that RHS is an integer vector type with the
857 // same number of elts as lhs.
858 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000859 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000860 RHSType->getAs<VectorType>()->getNumElements() != numElements)
861 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
862 << SourceRange(TheCall->getArg(1)->getLocStart(),
863 TheCall->getArg(1)->getLocEnd());
864 numResElements = numElements;
865 }
866 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000867 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000868 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000869 TheCall->getArg(1)->getLocEnd());
870 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000871 } else if (numElements != numResElements) {
872 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000873 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000874 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000875 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000876 }
877
878 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000879 if (TheCall->getArg(i)->isTypeDependent() ||
880 TheCall->getArg(i)->isValueDependent())
881 continue;
882
Nate Begeman37b6a572010-06-08 00:16:34 +0000883 llvm::APSInt Result(32);
884 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
885 return ExprError(Diag(TheCall->getLocStart(),
886 diag::err_shufflevector_nonconstant_argument)
887 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000888
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000889 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000890 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000891 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000892 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000893 }
894
Chris Lattner5f9e2722011-07-23 10:55:15 +0000895 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +0000896
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000897 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000898 exprs.push_back(TheCall->getArg(i));
899 TheCall->setArg(i, 0);
900 }
901
Nate Begemana88dc302009-08-12 02:10:25 +0000902 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000903 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000904 TheCall->getCallee()->getLocStart(),
905 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000906}
Chris Lattner30ce3442007-12-19 23:59:04 +0000907
Daniel Dunbar4493f792008-07-21 22:59:13 +0000908/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
909// This is declared to take (const void*, ...) and can take two
910// optional constant int args.
911bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000912 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000913
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000914 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000915 return Diag(TheCall->getLocEnd(),
916 diag::err_typecheck_call_too_many_args_at_most)
917 << 0 /*function call*/ << 3 << NumArgs
918 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000919
920 // Argument 0 is checked for us and the remaining arguments must be
921 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000922 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000923 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000924
Eli Friedman9aef7262009-12-04 00:30:06 +0000925 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000926 if (SemaBuiltinConstantArg(TheCall, i, Result))
927 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Daniel Dunbar4493f792008-07-21 22:59:13 +0000929 // FIXME: gcc issues a warning and rewrites these to 0. These
930 // seems especially odd for the third argument since the default
931 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000932 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000933 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000934 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000935 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000936 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000937 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000938 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000939 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000940 }
941 }
942
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000943 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000944}
945
Eric Christopher691ebc32010-04-17 02:26:23 +0000946/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
947/// TheCall is a constant expression.
948bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
949 llvm::APSInt &Result) {
950 Expr *Arg = TheCall->getArg(ArgNum);
951 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
952 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
953
954 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
955
956 if (!Arg->isIntegerConstantExpr(Result, Context))
957 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000958 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000959
Chris Lattner21fb98e2009-09-23 06:06:36 +0000960 return false;
961}
962
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000963/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
964/// int type). This simply type checks that type is one of the defined
965/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000966// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000967bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000968 llvm::APSInt Result;
969
970 // Check constant-ness first.
971 if (SemaBuiltinConstantArg(TheCall, 1, Result))
972 return true;
973
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000974 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000975 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000976 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
977 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000978 }
979
980 return false;
981}
982
Eli Friedman586d6a82009-05-03 06:04:26 +0000983/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000984/// This checks that val is a constant 1.
985bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
986 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000987 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000988
Eric Christopher691ebc32010-04-17 02:26:23 +0000989 // TODO: This is less than ideal. Overload this to take a value.
990 if (SemaBuiltinConstantArg(TheCall, 1, Result))
991 return true;
992
993 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000994 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
995 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
996
997 return false;
998}
999
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001000// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001001bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1002 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001003 unsigned format_idx, unsigned firstDataArg,
1004 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001005 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001006 if (E->isTypeDependent() || E->isValueDependent())
1007 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001008
Peter Collingbournef111d932011-04-15 00:35:48 +00001009 E = E->IgnoreParens();
1010
Ted Kremenekd30ef872009-01-12 23:09:09 +00001011 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001012 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001013 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001014 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001015 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1016 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +00001017 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001018 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001019 }
1020
Ted Kremenek95355bb2010-09-09 03:51:42 +00001021 case Stmt::IntegerLiteralClass:
1022 // Technically -Wformat-nonliteral does not warn about this case.
1023 // The behavior of printf and friends in this case is implementation
1024 // dependent. Ideally if the format string cannot be null then
1025 // it should have a 'nonnull' attribute in the function prototype.
1026 return true;
1027
Ted Kremenekd30ef872009-01-12 23:09:09 +00001028 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001029 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1030 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001031 }
1032
John McCall56ca35d2011-02-17 10:25:35 +00001033 case Stmt::OpaqueValueExprClass:
1034 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1035 E = src;
1036 goto tryAgain;
1037 }
1038 return false;
1039
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001040 case Stmt::PredefinedExprClass:
1041 // While __func__, etc., are technically not string literals, they
1042 // cannot contain format specifiers and thus are not a security
1043 // liability.
1044 return true;
1045
Ted Kremenek082d9362009-03-20 21:35:28 +00001046 case Stmt::DeclRefExprClass: {
1047 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Ted Kremenek082d9362009-03-20 21:35:28 +00001049 // As an exception, do not flag errors for variables binding to
1050 // const string literals.
1051 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1052 bool isConstant = false;
1053 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001054
Ted Kremenek082d9362009-03-20 21:35:28 +00001055 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1056 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001057 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001058 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001059 PT->getPointeeType().isConstant(Context);
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Ted Kremenek082d9362009-03-20 21:35:28 +00001062 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001063 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001064 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001065 HasVAListArg, format_idx, firstDataArg,
1066 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001067 }
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Anders Carlssond966a552009-06-28 19:55:58 +00001069 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1070 // special check to see if the format string is a function parameter
1071 // of the function calling the printf function. If the function
1072 // has an attribute indicating it is a printf-like function, then we
1073 // should suppress warnings concerning non-literals being used in a call
1074 // to a vprintf function. For example:
1075 //
1076 // void
1077 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1078 // va_list ap;
1079 // va_start(ap, fmt);
1080 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1081 // ...
1082 //
1083 //
1084 // FIXME: We don't have full attribute support yet, so just check to see
1085 // if the argument is a DeclRefExpr that references a parameter. We'll
1086 // add proper support for checking the attribute later.
1087 if (HasVAListArg)
1088 if (isa<ParmVarDecl>(VD))
1089 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001090 }
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Ted Kremenek082d9362009-03-20 21:35:28 +00001092 return false;
1093 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001094
Anders Carlsson8f031b32009-06-27 04:05:33 +00001095 case Stmt::CallExprClass: {
1096 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001097 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001098 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1099 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1100 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001101 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001102 unsigned ArgIndex = FA->getFormatIdx();
1103 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
1105 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001106 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001107 }
1108 }
1109 }
1110 }
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Anders Carlsson8f031b32009-06-27 04:05:33 +00001112 return false;
1113 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001114 case Stmt::ObjCStringLiteralClass:
1115 case Stmt::StringLiteralClass: {
1116 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Ted Kremenek082d9362009-03-20 21:35:28 +00001118 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001119 StrE = ObjCFExpr->getString();
1120 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001121 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Ted Kremenekd30ef872009-01-12 23:09:09 +00001123 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001124 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1125 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001126 return true;
1127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Ted Kremenekd30ef872009-01-12 23:09:09 +00001129 return false;
1130 }
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Ted Kremenek082d9362009-03-20 21:35:28 +00001132 default:
1133 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001134 }
1135}
1136
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001137void
Mike Stump1eb44332009-09-09 15:08:12 +00001138Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001139 const Expr * const *ExprArgs,
1140 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001141 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1142 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001143 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001144 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001145 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001146 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001147 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001148 }
1149}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001150
Ted Kremenek826a3452010-07-16 02:11:22 +00001151/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1152/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001153void
Ted Kremenek826a3452010-07-16 02:11:22 +00001154Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1155 unsigned format_idx, unsigned firstDataArg,
1156 bool isPrintf) {
1157
Ted Kremenek082d9362009-03-20 21:35:28 +00001158 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001159
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001160 // The way the format attribute works in GCC, the implicit this argument
1161 // of member functions is counted. However, it doesn't appear in our own
1162 // lists, so decrement format_idx in that case.
1163 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001164 const CXXMethodDecl *method_decl =
1165 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1166 if (method_decl && method_decl->isInstance()) {
1167 // Catch a format attribute mistakenly referring to the object argument.
1168 if (format_idx == 0)
1169 return;
1170 --format_idx;
1171 if(firstDataArg != 0)
1172 --firstDataArg;
1173 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001174 }
1175
Ted Kremenek826a3452010-07-16 02:11:22 +00001176 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001177 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001178 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001179 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001180 return;
1181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Ted Kremenek082d9362009-03-20 21:35:28 +00001183 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Chris Lattner59907c42007-08-10 20:18:51 +00001185 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001186 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001187 // Dynamically generated format strings are difficult to
1188 // automatically vet at compile time. Requiring that format strings
1189 // are string literals: (1) permits the checking of format strings by
1190 // the compiler and thereby (2) can practically remove the source of
1191 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001192
Mike Stump1eb44332009-09-09 15:08:12 +00001193 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001194 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001195 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001196 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001197 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001198 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001199 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001200
Chris Lattner655f1412009-04-29 04:59:47 +00001201 // If there are no arguments specified, warn with -Wformat-security, otherwise
1202 // warn only with -Wformat-nonliteral.
1203 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001204 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001205 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001206 << OrigFormatExpr->getSourceRange();
1207 else
Mike Stump1eb44332009-09-09 15:08:12 +00001208 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001209 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001210 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001211}
Ted Kremenek71895b92007-08-14 17:39:48 +00001212
Ted Kremeneke0e53132010-01-28 23:39:18 +00001213namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001214class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1215protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001216 Sema &S;
1217 const StringLiteral *FExpr;
1218 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001219 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001220 const unsigned NumDataArgs;
1221 const bool IsObjCLiteral;
1222 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001223 const bool HasVAListArg;
1224 const CallExpr *TheCall;
1225 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001226 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001227 bool usesPositionalArgs;
1228 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001229public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001230 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001231 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001232 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001233 const char *beg, bool hasVAListArg,
1234 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001235 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001236 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001237 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001238 IsObjCLiteral(isObjCLiteral), Beg(beg),
1239 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001240 TheCall(theCall), FormatIdx(formatIdx),
1241 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001242 CoveredArgs.resize(numDataArgs);
1243 CoveredArgs.reset();
1244 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001245
Ted Kremenek07d161f2010-01-29 01:50:07 +00001246 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001247
Ted Kremenek826a3452010-07-16 02:11:22 +00001248 void HandleIncompleteSpecifier(const char *startSpecifier,
1249 unsigned specifierLen);
1250
Ted Kremenekefaff192010-02-27 01:41:03 +00001251 virtual void HandleInvalidPosition(const char *startSpecifier,
1252 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001253 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001254
1255 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1256
Ted Kremeneke0e53132010-01-28 23:39:18 +00001257 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001258
Ted Kremenek826a3452010-07-16 02:11:22 +00001259protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001260 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1261 const char *startSpec,
1262 unsigned specifierLen,
1263 const char *csStart, unsigned csLen);
1264
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001265 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001266 CharSourceRange getSpecifierRange(const char *startSpecifier,
1267 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001268 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001269
Ted Kremenek0d277352010-01-29 01:06:55 +00001270 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001271
1272 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1273 const analyze_format_string::ConversionSpecifier &CS,
1274 const char *startSpecifier, unsigned specifierLen,
1275 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001276};
1277}
1278
Ted Kremenek826a3452010-07-16 02:11:22 +00001279SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001280 return OrigFormatExpr->getSourceRange();
1281}
1282
Ted Kremenek826a3452010-07-16 02:11:22 +00001283CharSourceRange CheckFormatHandler::
1284getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001285 SourceLocation Start = getLocationOfByte(startSpecifier);
1286 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1287
1288 // Advance the end SourceLocation by one due to half-open ranges.
1289 End = End.getFileLocWithOffset(1);
1290
1291 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001292}
1293
Ted Kremenek826a3452010-07-16 02:11:22 +00001294SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001295 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001296}
1297
Ted Kremenek826a3452010-07-16 02:11:22 +00001298void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1299 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001300 SourceLocation Loc = getLocationOfByte(startSpecifier);
1301 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001302 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001303}
1304
Ted Kremenekefaff192010-02-27 01:41:03 +00001305void
Ted Kremenek826a3452010-07-16 02:11:22 +00001306CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1307 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001308 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001309 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1310 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001311}
1312
Ted Kremenek826a3452010-07-16 02:11:22 +00001313void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001314 unsigned posLen) {
1315 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001316 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1317 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001318}
1319
Ted Kremenek826a3452010-07-16 02:11:22 +00001320void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001321 if (!IsObjCLiteral) {
1322 // The presence of a null character is likely an error.
1323 S.Diag(getLocationOfByte(nullCharacter),
1324 diag::warn_printf_format_string_contains_null_char)
1325 << getFormatStringRange();
1326 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001327}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001328
Ted Kremenek826a3452010-07-16 02:11:22 +00001329const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1330 return TheCall->getArg(FirstDataArg + i);
1331}
1332
1333void CheckFormatHandler::DoneProcessing() {
1334 // Does the number of data arguments exceed the number of
1335 // format conversions in the format string?
1336 if (!HasVAListArg) {
1337 // Find any arguments that weren't covered.
1338 CoveredArgs.flip();
1339 signed notCoveredArg = CoveredArgs.find_first();
1340 if (notCoveredArg >= 0) {
1341 assert((unsigned)notCoveredArg < NumDataArgs);
1342 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1343 diag::warn_printf_data_arg_not_used)
1344 << getFormatStringRange();
1345 }
1346 }
1347}
1348
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001349bool
1350CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1351 SourceLocation Loc,
1352 const char *startSpec,
1353 unsigned specifierLen,
1354 const char *csStart,
1355 unsigned csLen) {
1356
1357 bool keepGoing = true;
1358 if (argIndex < NumDataArgs) {
1359 // Consider the argument coverered, even though the specifier doesn't
1360 // make sense.
1361 CoveredArgs.set(argIndex);
1362 }
1363 else {
1364 // If argIndex exceeds the number of data arguments we
1365 // don't issue a warning because that is just a cascade of warnings (and
1366 // they may have intended '%%' anyway). We don't want to continue processing
1367 // the format string after this point, however, as we will like just get
1368 // gibberish when trying to match arguments.
1369 keepGoing = false;
1370 }
1371
1372 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001373 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001374 << getSpecifierRange(startSpec, specifierLen);
1375
1376 return keepGoing;
1377}
1378
Ted Kremenek666a1972010-07-26 19:45:42 +00001379bool
1380CheckFormatHandler::CheckNumArgs(
1381 const analyze_format_string::FormatSpecifier &FS,
1382 const analyze_format_string::ConversionSpecifier &CS,
1383 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1384
1385 if (argIndex >= NumDataArgs) {
1386 if (FS.usesPositionalArg()) {
1387 S.Diag(getLocationOfByte(CS.getStart()),
1388 diag::warn_printf_positional_arg_exceeds_data_args)
1389 << (argIndex+1) << NumDataArgs
1390 << getSpecifierRange(startSpecifier, specifierLen);
1391 }
1392 else {
1393 S.Diag(getLocationOfByte(CS.getStart()),
1394 diag::warn_printf_insufficient_data_args)
1395 << getSpecifierRange(startSpecifier, specifierLen);
1396 }
1397
1398 return false;
1399 }
1400 return true;
1401}
1402
Ted Kremenek826a3452010-07-16 02:11:22 +00001403//===--- CHECK: Printf format string checking ------------------------------===//
1404
1405namespace {
1406class CheckPrintfHandler : public CheckFormatHandler {
1407public:
1408 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1409 const Expr *origFormatExpr, unsigned firstDataArg,
1410 unsigned numDataArgs, bool isObjCLiteral,
1411 const char *beg, bool hasVAListArg,
1412 const CallExpr *theCall, unsigned formatIdx)
1413 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1414 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1415 theCall, formatIdx) {}
1416
1417
1418 bool HandleInvalidPrintfConversionSpecifier(
1419 const analyze_printf::PrintfSpecifier &FS,
1420 const char *startSpecifier,
1421 unsigned specifierLen);
1422
1423 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1424 const char *startSpecifier,
1425 unsigned specifierLen);
1426
1427 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1428 const char *startSpecifier, unsigned specifierLen);
1429 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1430 const analyze_printf::OptionalAmount &Amt,
1431 unsigned type,
1432 const char *startSpecifier, unsigned specifierLen);
1433 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1434 const analyze_printf::OptionalFlag &flag,
1435 const char *startSpecifier, unsigned specifierLen);
1436 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1437 const analyze_printf::OptionalFlag &ignoredFlag,
1438 const analyze_printf::OptionalFlag &flag,
1439 const char *startSpecifier, unsigned specifierLen);
1440};
1441}
1442
1443bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1444 const analyze_printf::PrintfSpecifier &FS,
1445 const char *startSpecifier,
1446 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001447 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001448 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001449
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001450 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1451 getLocationOfByte(CS.getStart()),
1452 startSpecifier, specifierLen,
1453 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001454}
1455
Ted Kremenek826a3452010-07-16 02:11:22 +00001456bool CheckPrintfHandler::HandleAmount(
1457 const analyze_format_string::OptionalAmount &Amt,
1458 unsigned k, const char *startSpecifier,
1459 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001460
1461 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001462 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001463 unsigned argIndex = Amt.getArgIndex();
1464 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001465 S.Diag(getLocationOfByte(Amt.getStart()),
1466 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001467 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001468 // Don't do any more checking. We will just emit
1469 // spurious errors.
1470 return false;
1471 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001472
Ted Kremenek0d277352010-01-29 01:06:55 +00001473 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001474 // Although not in conformance with C99, we also allow the argument to be
1475 // an 'unsigned int' as that is a reasonably safe case. GCC also
1476 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001477 CoveredArgs.set(argIndex);
1478 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001479 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001480
1481 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1482 assert(ATR.isValid());
1483
1484 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001485 S.Diag(getLocationOfByte(Amt.getStart()),
1486 diag::warn_printf_asterisk_wrong_type)
1487 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001488 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001489 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001490 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001491 // Don't do any more checking. We will just emit
1492 // spurious errors.
1493 return false;
1494 }
1495 }
1496 }
1497 return true;
1498}
Ted Kremenek0d277352010-01-29 01:06:55 +00001499
Tom Caree4ee9662010-06-17 19:00:27 +00001500void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001501 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001502 const analyze_printf::OptionalAmount &Amt,
1503 unsigned type,
1504 const char *startSpecifier,
1505 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001506 const analyze_printf::PrintfConversionSpecifier &CS =
1507 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001508 switch (Amt.getHowSpecified()) {
1509 case analyze_printf::OptionalAmount::Constant:
1510 S.Diag(getLocationOfByte(Amt.getStart()),
1511 diag::warn_printf_nonsensical_optional_amount)
1512 << type
1513 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001514 << getSpecifierRange(startSpecifier, specifierLen)
1515 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001516 Amt.getConstantLength()));
1517 break;
1518
1519 default:
1520 S.Diag(getLocationOfByte(Amt.getStart()),
1521 diag::warn_printf_nonsensical_optional_amount)
1522 << type
1523 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001524 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001525 break;
1526 }
1527}
1528
Ted Kremenek826a3452010-07-16 02:11:22 +00001529void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001530 const analyze_printf::OptionalFlag &flag,
1531 const char *startSpecifier,
1532 unsigned specifierLen) {
1533 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001534 const analyze_printf::PrintfConversionSpecifier &CS =
1535 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001536 S.Diag(getLocationOfByte(flag.getPosition()),
1537 diag::warn_printf_nonsensical_flag)
1538 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001539 << getSpecifierRange(startSpecifier, specifierLen)
1540 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001541}
1542
1543void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001544 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001545 const analyze_printf::OptionalFlag &ignoredFlag,
1546 const analyze_printf::OptionalFlag &flag,
1547 const char *startSpecifier,
1548 unsigned specifierLen) {
1549 // Warn about ignored flag with a fixit removal.
1550 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1551 diag::warn_printf_ignored_flag)
1552 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001553 << getSpecifierRange(startSpecifier, specifierLen)
1554 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001555 ignoredFlag.getPosition(), 1));
1556}
1557
Ted Kremeneke0e53132010-01-28 23:39:18 +00001558bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001559CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001560 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001561 const char *startSpecifier,
1562 unsigned specifierLen) {
1563
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001564 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001565 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001566 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001567
Ted Kremenekbaa40062010-07-19 22:01:06 +00001568 if (FS.consumesDataArgument()) {
1569 if (atFirstArg) {
1570 atFirstArg = false;
1571 usesPositionalArgs = FS.usesPositionalArg();
1572 }
1573 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1574 // Cannot mix-and-match positional and non-positional arguments.
1575 S.Diag(getLocationOfByte(CS.getStart()),
1576 diag::warn_format_mix_positional_nonpositional_args)
1577 << getSpecifierRange(startSpecifier, specifierLen);
1578 return false;
1579 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001580 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001581
Ted Kremenekefaff192010-02-27 01:41:03 +00001582 // First check if the field width, precision, and conversion specifier
1583 // have matching data arguments.
1584 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1585 startSpecifier, specifierLen)) {
1586 return false;
1587 }
1588
1589 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1590 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001591 return false;
1592 }
1593
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001594 if (!CS.consumesDataArgument()) {
1595 // FIXME: Technically specifying a precision or field width here
1596 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001597 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001598 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001599
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001600 // Consume the argument.
1601 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001602 if (argIndex < NumDataArgs) {
1603 // The check to see if the argIndex is valid will come later.
1604 // We set the bit here because we may exit early from this
1605 // function if we encounter some other error.
1606 CoveredArgs.set(argIndex);
1607 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001608
1609 // Check for using an Objective-C specific conversion specifier
1610 // in a non-ObjC literal.
1611 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001612 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1613 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001614 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001615
Tom Caree4ee9662010-06-17 19:00:27 +00001616 // Check for invalid use of field width
1617 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001618 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001619 startSpecifier, specifierLen);
1620 }
1621
1622 // Check for invalid use of precision
1623 if (!FS.hasValidPrecision()) {
1624 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1625 startSpecifier, specifierLen);
1626 }
1627
1628 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001629 if (!FS.hasValidThousandsGroupingPrefix())
1630 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001631 if (!FS.hasValidLeadingZeros())
1632 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1633 if (!FS.hasValidPlusPrefix())
1634 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001635 if (!FS.hasValidSpacePrefix())
1636 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001637 if (!FS.hasValidAlternativeForm())
1638 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1639 if (!FS.hasValidLeftJustified())
1640 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1641
1642 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001643 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1644 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1645 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001646 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1647 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1648 startSpecifier, specifierLen);
1649
1650 // Check the length modifier is valid with the given conversion specifier.
1651 const LengthModifier &LM = FS.getLengthModifier();
1652 if (!FS.hasValidLengthModifier())
1653 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001654 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001655 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001656 << getSpecifierRange(startSpecifier, specifierLen)
1657 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001658 LM.getLength()));
1659
1660 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001661 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001662 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001663 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001664 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001665 // Continue checking the other format specifiers.
1666 return true;
1667 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001668
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001669 // The remaining checks depend on the data arguments.
1670 if (HasVAListArg)
1671 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001672
Ted Kremenek666a1972010-07-26 19:45:42 +00001673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001674 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001675
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001676 // Now type check the data expression that matches the
1677 // format specifier.
1678 const Expr *Ex = getDataArg(argIndex);
1679 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1680 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1681 // Check if we didn't match because of an implicit cast from a 'char'
1682 // or 'short' to an 'int'. This is done because printf is a varargs
1683 // function.
1684 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001685 if (ICE->getType() == S.Context.IntTy) {
1686 // All further checking is done on the subexpression.
1687 Ex = ICE->getSubExpr();
1688 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001689 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001690 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001691
1692 // We may be able to offer a FixItHint if it is a supported type.
1693 PrintfSpecifier fixedFS = FS;
1694 bool success = fixedFS.fixType(Ex->getType());
1695
1696 if (success) {
1697 // Get the fix string from the fixed format specifier
1698 llvm::SmallString<128> buf;
1699 llvm::raw_svector_ostream os(buf);
1700 fixedFS.toString(os);
1701
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001702 // FIXME: getRepresentativeType() perhaps should return a string
1703 // instead of a QualType to better handle when the representative
1704 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001705 S.Diag(getLocationOfByte(CS.getStart()),
1706 diag::warn_printf_conversion_argument_type_mismatch)
1707 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1708 << getSpecifierRange(startSpecifier, specifierLen)
1709 << Ex->getSourceRange()
1710 << FixItHint::CreateReplacement(
1711 getSpecifierRange(startSpecifier, specifierLen),
1712 os.str());
1713 }
1714 else {
1715 S.Diag(getLocationOfByte(CS.getStart()),
1716 diag::warn_printf_conversion_argument_type_mismatch)
1717 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1718 << getSpecifierRange(startSpecifier, specifierLen)
1719 << Ex->getSourceRange();
1720 }
1721 }
1722
Ted Kremeneke0e53132010-01-28 23:39:18 +00001723 return true;
1724}
1725
Ted Kremenek826a3452010-07-16 02:11:22 +00001726//===--- CHECK: Scanf format string checking ------------------------------===//
1727
1728namespace {
1729class CheckScanfHandler : public CheckFormatHandler {
1730public:
1731 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1732 const Expr *origFormatExpr, unsigned firstDataArg,
1733 unsigned numDataArgs, bool isObjCLiteral,
1734 const char *beg, bool hasVAListArg,
1735 const CallExpr *theCall, unsigned formatIdx)
1736 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1737 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1738 theCall, formatIdx) {}
1739
1740 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1741 const char *startSpecifier,
1742 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001743
1744 bool HandleInvalidScanfConversionSpecifier(
1745 const analyze_scanf::ScanfSpecifier &FS,
1746 const char *startSpecifier,
1747 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001748
1749 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001750};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001751}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001752
Ted Kremenekb7c21012010-07-16 18:28:03 +00001753void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1754 const char *end) {
1755 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1756 << getSpecifierRange(start, end - start);
1757}
1758
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001759bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1760 const analyze_scanf::ScanfSpecifier &FS,
1761 const char *startSpecifier,
1762 unsigned specifierLen) {
1763
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001764 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001765 FS.getConversionSpecifier();
1766
1767 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1768 getLocationOfByte(CS.getStart()),
1769 startSpecifier, specifierLen,
1770 CS.getStart(), CS.getLength());
1771}
1772
Ted Kremenek826a3452010-07-16 02:11:22 +00001773bool CheckScanfHandler::HandleScanfSpecifier(
1774 const analyze_scanf::ScanfSpecifier &FS,
1775 const char *startSpecifier,
1776 unsigned specifierLen) {
1777
1778 using namespace analyze_scanf;
1779 using namespace analyze_format_string;
1780
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001781 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001782
Ted Kremenekbaa40062010-07-19 22:01:06 +00001783 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1784 // be used to decide if we are using positional arguments consistently.
1785 if (FS.consumesDataArgument()) {
1786 if (atFirstArg) {
1787 atFirstArg = false;
1788 usesPositionalArgs = FS.usesPositionalArg();
1789 }
1790 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1791 // Cannot mix-and-match positional and non-positional arguments.
1792 S.Diag(getLocationOfByte(CS.getStart()),
1793 diag::warn_format_mix_positional_nonpositional_args)
1794 << getSpecifierRange(startSpecifier, specifierLen);
1795 return false;
1796 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001797 }
1798
1799 // Check if the field with is non-zero.
1800 const OptionalAmount &Amt = FS.getFieldWidth();
1801 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1802 if (Amt.getConstantAmount() == 0) {
1803 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1804 Amt.getConstantLength());
1805 S.Diag(getLocationOfByte(Amt.getStart()),
1806 diag::warn_scanf_nonzero_width)
1807 << R << FixItHint::CreateRemoval(R);
1808 }
1809 }
1810
1811 if (!FS.consumesDataArgument()) {
1812 // FIXME: Technically specifying a precision or field width here
1813 // makes no sense. Worth issuing a warning at some point.
1814 return true;
1815 }
1816
1817 // Consume the argument.
1818 unsigned argIndex = FS.getArgIndex();
1819 if (argIndex < NumDataArgs) {
1820 // The check to see if the argIndex is valid will come later.
1821 // We set the bit here because we may exit early from this
1822 // function if we encounter some other error.
1823 CoveredArgs.set(argIndex);
1824 }
1825
Ted Kremenek1e51c202010-07-20 20:04:47 +00001826 // Check the length modifier is valid with the given conversion specifier.
1827 const LengthModifier &LM = FS.getLengthModifier();
1828 if (!FS.hasValidLengthModifier()) {
1829 S.Diag(getLocationOfByte(LM.getStart()),
1830 diag::warn_format_nonsensical_length)
1831 << LM.toString() << CS.toString()
1832 << getSpecifierRange(startSpecifier, specifierLen)
1833 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1834 LM.getLength()));
1835 }
1836
Ted Kremenek826a3452010-07-16 02:11:22 +00001837 // The remaining checks depend on the data arguments.
1838 if (HasVAListArg)
1839 return true;
1840
Ted Kremenek666a1972010-07-26 19:45:42 +00001841 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001842 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001843
1844 // FIXME: Check that the argument type matches the format specifier.
1845
1846 return true;
1847}
1848
1849void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001850 const Expr *OrigFormatExpr,
1851 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001852 unsigned format_idx, unsigned firstDataArg,
1853 bool isPrintf) {
1854
Ted Kremeneke0e53132010-01-28 23:39:18 +00001855 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00001856 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001857 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001858 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001859 << OrigFormatExpr->getSourceRange();
1860 return;
1861 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001862
Ted Kremeneke0e53132010-01-28 23:39:18 +00001863 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00001864 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001865 const char *Str = StrRef.data();
1866 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001867
Ted Kremeneke0e53132010-01-28 23:39:18 +00001868 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001869 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001870 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001871 << OrigFormatExpr->getSourceRange();
1872 return;
1873 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001874
1875 if (isPrintf) {
1876 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1877 TheCall->getNumArgs() - firstDataArg,
1878 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1879 HasVAListArg, TheCall, format_idx);
1880
1881 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1882 H.DoneProcessing();
1883 }
1884 else {
1885 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1886 TheCall->getNumArgs() - firstDataArg,
1887 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1888 HasVAListArg, TheCall, format_idx);
1889
1890 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1891 H.DoneProcessing();
1892 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001893}
1894
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001895//===--- CHECK: Standard memory functions ---------------------------------===//
1896
Douglas Gregor2a053a32011-05-03 20:05:22 +00001897/// \brief Determine whether the given type is a dynamic class type (e.g.,
1898/// whether it has a vtable).
1899static bool isDynamicClassType(QualType T) {
1900 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1901 if (CXXRecordDecl *Definition = Record->getDefinition())
1902 if (Definition->isDynamicClass())
1903 return true;
1904
1905 return false;
1906}
1907
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001908/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00001909/// otherwise returns NULL.
1910static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001911 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001912 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1913 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1914 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001915
Chandler Carruth000d4282011-06-16 09:09:40 +00001916 return 0;
1917}
1918
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001919/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00001920static QualType getSizeOfArgType(const Expr* E) {
1921 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1922 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1923 if (SizeOf->getKind() == clang::UETT_SizeOf)
1924 return SizeOf->getTypeOfArgument();
1925
1926 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001927}
1928
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001929/// \brief Check for dangerous or invalid arguments to memset().
1930///
Chandler Carruth929f0132011-06-03 06:23:57 +00001931/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001932/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
1933/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001934///
1935/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001936void Sema::CheckMemaccessArguments(const CallExpr *Call,
1937 CheckedMemoryFunction CMF,
1938 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001939 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00001940 // we have enough arguments, and if not, abort further checking.
1941 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001942 return;
1943
Douglas Gregor707a23e2011-06-16 17:56:04 +00001944 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00001945 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001946
1947 // We have special checking when the length is a sizeof expression.
1948 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1949 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1950 llvm::FoldingSetNodeID SizeOfArgID;
1951
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001952 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1953 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001954 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001955
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001956 QualType DestTy = Dest->getType();
1957 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1958 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001959
Chandler Carruth000d4282011-06-16 09:09:40 +00001960 // Never warn about void type pointers. This can be used to suppress
1961 // false positives.
1962 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001963 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001964
Chandler Carruth000d4282011-06-16 09:09:40 +00001965 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1966 // actually comparing the expressions for equality. Because computing the
1967 // expression IDs can be expensive, we only do this if the diagnostic is
1968 // enabled.
1969 if (SizeOfArg &&
1970 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1971 SizeOfArg->getExprLoc())) {
1972 // We only compute IDs for expressions if the warning is enabled, and
1973 // cache the sizeof arg's ID.
1974 if (SizeOfArgID == llvm::FoldingSetNodeID())
1975 SizeOfArg->Profile(SizeOfArgID, Context, true);
1976 llvm::FoldingSetNodeID DestID;
1977 Dest->Profile(DestID, Context, true);
1978 if (DestID == SizeOfArgID) {
1979 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1980 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1981 if (UnaryOp->getOpcode() == UO_AddrOf)
1982 ActionIdx = 1; // If its an address-of operator, just remove it.
1983 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1984 ActionIdx = 2; // If the pointee's size is sizeof(char),
1985 // suggest an explicit length.
1986 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1987 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1988 << FnName << ArgIdx << ActionIdx
1989 << Dest->getSourceRange()
1990 << SizeOfArg->getSourceRange());
1991 break;
1992 }
1993 }
1994
1995 // Also check for cases where the sizeof argument is the exact same
1996 // type as the memory argument, and where it points to a user-defined
1997 // record type.
1998 if (SizeOfArgTy != QualType()) {
1999 if (PointeeTy->isRecordType() &&
2000 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2001 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2002 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2003 << FnName << SizeOfArgTy << ArgIdx
2004 << PointeeTy << Dest->getSourceRange()
2005 << LenExpr->getSourceRange());
2006 break;
2007 }
Nico Webere4a1c642011-06-14 16:14:58 +00002008 }
2009
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002010 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002011 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002012 DiagRuntimeBehavior(
2013 Dest->getExprLoc(), Dest,
2014 PDiag(diag::warn_dyn_class_memaccess)
2015 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2016 // "overwritten" if we're warning about the destination for any call
2017 // but memcmp; otherwise a verb appropriate to the call.
2018 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2019 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002020 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002021 DiagRuntimeBehavior(
2022 Dest->getExprLoc(), Dest,
2023 PDiag(diag::warn_arc_object_memaccess)
2024 << ArgIdx << FnName << PointeeTy
2025 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002026 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002027 continue;
John McCallf85e1932011-06-15 23:02:42 +00002028
2029 DiagRuntimeBehavior(
2030 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002031 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002032 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2033 break;
2034 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002035 }
2036}
2037
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002038// A little helper routine: ignore addition and subtraction of integer literals.
2039// This intentionally does not ignore all integer constant expressions because
2040// we don't want to remove sizeof().
2041static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2042 Ex = Ex->IgnoreParenCasts();
2043
2044 for (;;) {
2045 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2046 if (!BO || !BO->isAdditiveOp())
2047 break;
2048
2049 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2050 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2051
2052 if (isa<IntegerLiteral>(RHS))
2053 Ex = LHS;
2054 else if (isa<IntegerLiteral>(LHS))
2055 Ex = RHS;
2056 else
2057 break;
2058 }
2059
2060 return Ex;
2061}
2062
2063// Warn if the user has made the 'size' argument to strlcpy or strlcat
2064// be the size of the source, instead of the destination.
2065void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2066 IdentifierInfo *FnName) {
2067
2068 // Don't crash if the user has the wrong number of arguments
2069 if (Call->getNumArgs() != 3)
2070 return;
2071
2072 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2073 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2074 const Expr *CompareWithSrc = NULL;
2075
2076 // Look for 'strlcpy(dst, x, sizeof(x))'
2077 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2078 CompareWithSrc = Ex;
2079 else {
2080 // Look for 'strlcpy(dst, x, strlen(x))'
2081 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2082 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2083 && SizeCall->getNumArgs() == 1)
2084 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2085 }
2086 }
2087
2088 if (!CompareWithSrc)
2089 return;
2090
2091 // Determine if the argument to sizeof/strlen is equal to the source
2092 // argument. In principle there's all kinds of things you could do
2093 // here, for instance creating an == expression and evaluating it with
2094 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2095 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2096 if (!SrcArgDRE)
2097 return;
2098
2099 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2100 if (!CompareWithSrcDRE ||
2101 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2102 return;
2103
2104 const Expr *OriginalSizeArg = Call->getArg(2);
2105 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2106 << OriginalSizeArg->getSourceRange() << FnName;
2107
2108 // Output a FIXIT hint if the destination is an array (rather than a
2109 // pointer to an array). This could be enhanced to handle some
2110 // pointers if we know the actual size, like if DstArg is 'array+2'
2111 // we could say 'sizeof(array)-2'.
2112 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002113 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002114
Ted Kremenek8f746222011-08-18 22:48:41 +00002115 // Only handle constant-sized or VLAs, but not flexible members.
2116 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2117 // Only issue the FIXIT for arrays of size > 1.
2118 if (CAT->getSize().getSExtValue() <= 1)
2119 return;
2120 } else if (!DstArgTy->isVariableArrayType()) {
2121 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002122 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002123
2124 llvm::SmallString<128> sizeString;
2125 llvm::raw_svector_ostream OS(sizeString);
2126 OS << "sizeof(";
2127 DstArg->printPretty(OS, Context, 0, Context.PrintingPolicy);
2128 OS << ")";
2129
2130 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2131 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2132 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002133}
2134
Ted Kremenek06de2762007-08-17 16:46:58 +00002135//===--- CHECK: Return Address of Stack Variable --------------------------===//
2136
Chris Lattner5f9e2722011-07-23 10:55:15 +00002137static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2138static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002139
2140/// CheckReturnStackAddr - Check if a return statement returns the address
2141/// of a stack variable.
2142void
2143Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2144 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002146 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002147 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002148
2149 // Perform checking for returned stack addresses, local blocks,
2150 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002151 if (lhsType->isPointerType() ||
2152 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002153 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002154 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002155 stackE = EvalVal(RetValExp, refVars);
2156 }
2157
2158 if (stackE == 0)
2159 return; // Nothing suspicious was found.
2160
2161 SourceLocation diagLoc;
2162 SourceRange diagRange;
2163 if (refVars.empty()) {
2164 diagLoc = stackE->getLocStart();
2165 diagRange = stackE->getSourceRange();
2166 } else {
2167 // We followed through a reference variable. 'stackE' contains the
2168 // problematic expression but we will warn at the return statement pointing
2169 // at the reference variable. We will later display the "trail" of
2170 // reference variables using notes.
2171 diagLoc = refVars[0]->getLocStart();
2172 diagRange = refVars[0]->getSourceRange();
2173 }
2174
2175 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2176 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2177 : diag::warn_ret_stack_addr)
2178 << DR->getDecl()->getDeclName() << diagRange;
2179 } else if (isa<BlockExpr>(stackE)) { // local block.
2180 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2181 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2182 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2183 } else { // local temporary.
2184 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2185 : diag::warn_ret_local_temp_addr)
2186 << diagRange;
2187 }
2188
2189 // Display the "trail" of reference variables that we followed until we
2190 // found the problematic expression using notes.
2191 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2192 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2193 // If this var binds to another reference var, show the range of the next
2194 // var, otherwise the var binds to the problematic expression, in which case
2195 // show the range of the expression.
2196 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2197 : stackE->getSourceRange();
2198 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2199 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002200 }
2201}
2202
2203/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2204/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002205/// to a location on the stack, a local block, an address of a label, or a
2206/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002207/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002208/// encounter a subexpression that (1) clearly does not lead to one of the
2209/// above problematic expressions (2) is something we cannot determine leads to
2210/// a problematic expression based on such local checking.
2211///
2212/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2213/// the expression that they point to. Such variables are added to the
2214/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002215///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002216/// EvalAddr processes expressions that are pointers that are used as
2217/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002218/// At the base case of the recursion is a check for the above problematic
2219/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002220///
2221/// This implementation handles:
2222///
2223/// * pointer-to-pointer casts
2224/// * implicit conversions from array references to pointers
2225/// * taking the address of fields
2226/// * arbitrary interplay between "&" and "*" operators
2227/// * pointer arithmetic from an address of a stack variable
2228/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002229static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002230 if (E->isTypeDependent())
2231 return NULL;
2232
Ted Kremenek06de2762007-08-17 16:46:58 +00002233 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002234 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002235 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002237 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Peter Collingbournef111d932011-04-15 00:35:48 +00002239 E = E->IgnoreParens();
2240
Ted Kremenek06de2762007-08-17 16:46:58 +00002241 // Our "symbolic interpreter" is just a dispatch off the currently
2242 // viewed AST node. We then recursively traverse the AST by calling
2243 // EvalAddr and EvalVal appropriately.
2244 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002245 case Stmt::DeclRefExprClass: {
2246 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2247
2248 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2249 // If this is a reference variable, follow through to the expression that
2250 // it points to.
2251 if (V->hasLocalStorage() &&
2252 V->getType()->isReferenceType() && V->hasInit()) {
2253 // Add the reference variable to the "trail".
2254 refVars.push_back(DR);
2255 return EvalAddr(V->getInit(), refVars);
2256 }
2257
2258 return NULL;
2259 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002260
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002261 case Stmt::UnaryOperatorClass: {
2262 // The only unary operator that make sense to handle here
2263 // is AddrOf. All others don't make sense as pointers.
2264 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002265
John McCall2de56d12010-08-25 11:45:40 +00002266 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002267 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002268 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002269 return NULL;
2270 }
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002272 case Stmt::BinaryOperatorClass: {
2273 // Handle pointer arithmetic. All other binary operators are not valid
2274 // in this context.
2275 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002276 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002277
John McCall2de56d12010-08-25 11:45:40 +00002278 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002279 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002281 Expr *Base = B->getLHS();
2282
2283 // Determine which argument is the real pointer base. It could be
2284 // the RHS argument instead of the LHS.
2285 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002287 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002288 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002289 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002290
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002291 // For conditional operators we need to see if either the LHS or RHS are
2292 // valid DeclRefExpr*s. If one of them is valid, we return it.
2293 case Stmt::ConditionalOperatorClass: {
2294 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002296 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002297 if (Expr *lhsExpr = C->getLHS()) {
2298 // In C++, we can have a throw-expression, which has 'void' type.
2299 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002300 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002301 return LHS;
2302 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002303
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002304 // In C++, we can have a throw-expression, which has 'void' type.
2305 if (C->getRHS()->getType()->isVoidType())
2306 return NULL;
2307
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002308 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002309 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002310
2311 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002312 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002313 return E; // local block.
2314 return NULL;
2315
2316 case Stmt::AddrLabelExprClass:
2317 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Ted Kremenek54b52742008-08-07 00:49:01 +00002319 // For casts, we need to handle conversions from arrays to
2320 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002321 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002322 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002323 case Stmt::CXXFunctionalCastExprClass:
2324 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002325 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002326 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Steve Naroffdd972f22008-09-05 22:11:13 +00002328 if (SubExpr->getType()->isPointerType() ||
2329 SubExpr->getType()->isBlockPointerType() ||
2330 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002331 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002332 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002333 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002334 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002335 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002336 }
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002338 // C++ casts. For dynamic casts, static casts, and const casts, we
2339 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002340 // through the cast. In the case the dynamic cast doesn't fail (and
2341 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002342 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002343 // FIXME: The comment about is wrong; we're not always converting
2344 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002345 // handle references to objects.
2346 case Stmt::CXXStaticCastExprClass:
2347 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002348 case Stmt::CXXConstCastExprClass:
2349 case Stmt::CXXReinterpretCastExprClass: {
2350 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002351 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002352 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002353 else
2354 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002355 }
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Douglas Gregor03e80032011-06-21 17:03:29 +00002357 case Stmt::MaterializeTemporaryExprClass:
2358 if (Expr *Result = EvalAddr(
2359 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2360 refVars))
2361 return Result;
2362
2363 return E;
2364
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002365 // Everything else: we simply don't reason about them.
2366 default:
2367 return NULL;
2368 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002369}
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Ted Kremenek06de2762007-08-17 16:46:58 +00002371
2372/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2373/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002374static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002375do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002376 // We should only be called for evaluating non-pointer expressions, or
2377 // expressions with a pointer type that are not used as references but instead
2378 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Ted Kremenek06de2762007-08-17 16:46:58 +00002380 // Our "symbolic interpreter" is just a dispatch off the currently
2381 // viewed AST node. We then recursively traverse the AST by calling
2382 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002383
2384 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002385 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002386 case Stmt::ImplicitCastExprClass: {
2387 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002388 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002389 E = IE->getSubExpr();
2390 continue;
2391 }
2392 return NULL;
2393 }
2394
Douglas Gregora2813ce2009-10-23 18:54:35 +00002395 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002396 // When we hit a DeclRefExpr we are looking at code that refers to a
2397 // variable's name. If it's not a reference variable we check if it has
2398 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002399 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Ted Kremenek06de2762007-08-17 16:46:58 +00002401 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002402 if (V->hasLocalStorage()) {
2403 if (!V->getType()->isReferenceType())
2404 return DR;
2405
2406 // Reference variable, follow through to the expression that
2407 // it points to.
2408 if (V->hasInit()) {
2409 // Add the reference variable to the "trail".
2410 refVars.push_back(DR);
2411 return EvalVal(V->getInit(), refVars);
2412 }
2413 }
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Ted Kremenek06de2762007-08-17 16:46:58 +00002415 return NULL;
2416 }
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Ted Kremenek06de2762007-08-17 16:46:58 +00002418 case Stmt::UnaryOperatorClass: {
2419 // The only unary operator that make sense to handle here
2420 // is Deref. All others don't resolve to a "name." This includes
2421 // handling all sorts of rvalues passed to a unary operator.
2422 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002423
John McCall2de56d12010-08-25 11:45:40 +00002424 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002425 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002426
2427 return NULL;
2428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Ted Kremenek06de2762007-08-17 16:46:58 +00002430 case Stmt::ArraySubscriptExprClass: {
2431 // Array subscripts are potential references to data on the stack. We
2432 // retrieve the DeclRefExpr* for the array variable if it indeed
2433 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002434 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002435 }
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Ted Kremenek06de2762007-08-17 16:46:58 +00002437 case Stmt::ConditionalOperatorClass: {
2438 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002439 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002440 ConditionalOperator *C = cast<ConditionalOperator>(E);
2441
Anders Carlsson39073232007-11-30 19:04:31 +00002442 // Handle the GNU extension for missing LHS.
2443 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002444 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002445 return LHS;
2446
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002447 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Ted Kremenek06de2762007-08-17 16:46:58 +00002450 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002451 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002452 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Ted Kremenek06de2762007-08-17 16:46:58 +00002454 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002455 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002456 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002457
2458 // Check whether the member type is itself a reference, in which case
2459 // we're not going to refer to the member, but to what the member refers to.
2460 if (M->getMemberDecl()->getType()->isReferenceType())
2461 return NULL;
2462
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002463 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002464 }
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Douglas Gregor03e80032011-06-21 17:03:29 +00002466 case Stmt::MaterializeTemporaryExprClass:
2467 if (Expr *Result = EvalVal(
2468 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2469 refVars))
2470 return Result;
2471
2472 return E;
2473
Ted Kremenek06de2762007-08-17 16:46:58 +00002474 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002475 // Check that we don't return or take the address of a reference to a
2476 // temporary. This is only useful in C++.
2477 if (!E->isTypeDependent() && E->isRValue())
2478 return E;
2479
2480 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002481 return NULL;
2482 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002483} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002484}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002485
2486//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2487
2488/// Check for comparisons of floating point operands using != and ==.
2489/// Issue a warning if these are no self-comparisons, as they are not likely
2490/// to do what the programmer intended.
2491void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2492 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002493
John McCallf6a16482010-12-04 03:47:34 +00002494 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2495 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002496
2497 // Special case: check for x == x (which is OK).
2498 // Do not emit warnings for such cases.
2499 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2500 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2501 if (DRL->getDecl() == DRR->getDecl())
2502 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002503
2504
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002505 // Special case: check for comparisons against literals that can be exactly
2506 // represented by APFloat. In such cases, do not emit a warning. This
2507 // is a heuristic: often comparison against such literals are used to
2508 // detect if a value in a variable has not changed. This clearly can
2509 // lead to false negatives.
2510 if (EmitWarning) {
2511 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2512 if (FLL->isExact())
2513 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002514 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002515 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2516 if (FLR->isExact())
2517 EmitWarning = false;
2518 }
2519 }
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002521 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002522 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002523 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002524 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002525 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Sebastian Redl0eb23302009-01-19 00:08:26 +00002527 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002528 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002529 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002530 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002532 // Emit the diagnostic.
2533 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002534 Diag(loc, diag::warn_floatingpoint_eq)
2535 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002536}
John McCallba26e582010-01-04 23:21:16 +00002537
John McCallf2370c92010-01-06 05:24:50 +00002538//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2539//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002540
John McCallf2370c92010-01-06 05:24:50 +00002541namespace {
John McCallba26e582010-01-04 23:21:16 +00002542
John McCallf2370c92010-01-06 05:24:50 +00002543/// Structure recording the 'active' range of an integer-valued
2544/// expression.
2545struct IntRange {
2546 /// The number of bits active in the int.
2547 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002548
John McCallf2370c92010-01-06 05:24:50 +00002549 /// True if the int is known not to have negative values.
2550 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002551
John McCallf2370c92010-01-06 05:24:50 +00002552 IntRange(unsigned Width, bool NonNegative)
2553 : Width(Width), NonNegative(NonNegative)
2554 {}
John McCallba26e582010-01-04 23:21:16 +00002555
John McCall1844a6e2010-11-10 23:38:19 +00002556 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002557 static IntRange forBoolType() {
2558 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002559 }
2560
John McCall1844a6e2010-11-10 23:38:19 +00002561 /// Returns the range of an opaque value of the given integral type.
2562 static IntRange forValueOfType(ASTContext &C, QualType T) {
2563 return forValueOfCanonicalType(C,
2564 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002565 }
2566
John McCall1844a6e2010-11-10 23:38:19 +00002567 /// Returns the range of an opaque value of a canonical integral type.
2568 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002569 assert(T->isCanonicalUnqualified());
2570
2571 if (const VectorType *VT = dyn_cast<VectorType>(T))
2572 T = VT->getElementType().getTypePtr();
2573 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2574 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002575
John McCall091f23f2010-11-09 22:22:12 +00002576 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002577 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2578 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002579 if (!Enum->isDefinition())
2580 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2581
John McCall323ed742010-05-06 08:58:33 +00002582 unsigned NumPositive = Enum->getNumPositiveBits();
2583 unsigned NumNegative = Enum->getNumNegativeBits();
2584
2585 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2586 }
John McCallf2370c92010-01-06 05:24:50 +00002587
2588 const BuiltinType *BT = cast<BuiltinType>(T);
2589 assert(BT->isInteger());
2590
2591 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2592 }
2593
John McCall1844a6e2010-11-10 23:38:19 +00002594 /// Returns the "target" range of a canonical integral type, i.e.
2595 /// the range of values expressible in the type.
2596 ///
2597 /// This matches forValueOfCanonicalType except that enums have the
2598 /// full range of their type, not the range of their enumerators.
2599 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2600 assert(T->isCanonicalUnqualified());
2601
2602 if (const VectorType *VT = dyn_cast<VectorType>(T))
2603 T = VT->getElementType().getTypePtr();
2604 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2605 T = CT->getElementType().getTypePtr();
2606 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002607 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002608
2609 const BuiltinType *BT = cast<BuiltinType>(T);
2610 assert(BT->isInteger());
2611
2612 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2613 }
2614
2615 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002616 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002617 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002618 L.NonNegative && R.NonNegative);
2619 }
2620
John McCall1844a6e2010-11-10 23:38:19 +00002621 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002622 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002623 return IntRange(std::min(L.Width, R.Width),
2624 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002625 }
2626};
2627
2628IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2629 if (value.isSigned() && value.isNegative())
2630 return IntRange(value.getMinSignedBits(), false);
2631
2632 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002633 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002634
2635 // isNonNegative() just checks the sign bit without considering
2636 // signedness.
2637 return IntRange(value.getActiveBits(), true);
2638}
2639
John McCall0acc3112010-01-06 22:57:21 +00002640IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002641 unsigned MaxWidth) {
2642 if (result.isInt())
2643 return GetValueRange(C, result.getInt(), MaxWidth);
2644
2645 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002646 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2647 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2648 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2649 R = IntRange::join(R, El);
2650 }
John McCallf2370c92010-01-06 05:24:50 +00002651 return R;
2652 }
2653
2654 if (result.isComplexInt()) {
2655 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2656 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2657 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002658 }
2659
2660 // This can happen with lossless casts to intptr_t of "based" lvalues.
2661 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002662 // FIXME: The only reason we need to pass the type in here is to get
2663 // the sign right on this one case. It would be nice if APValue
2664 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002665 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002666 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002667}
John McCallf2370c92010-01-06 05:24:50 +00002668
2669/// Pseudo-evaluate the given integer expression, estimating the
2670/// range of values it might take.
2671///
2672/// \param MaxWidth - the width to which the value will be truncated
2673IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2674 E = E->IgnoreParens();
2675
2676 // Try a full evaluation first.
2677 Expr::EvalResult result;
2678 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002679 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002680
2681 // I think we only want to look through implicit casts here; if the
2682 // user has an explicit widening cast, we should treat the value as
2683 // being of the new, wider type.
2684 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002685 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002686 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2687
John McCall1844a6e2010-11-10 23:38:19 +00002688 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002689
John McCall2de56d12010-08-25 11:45:40 +00002690 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002691
John McCallf2370c92010-01-06 05:24:50 +00002692 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002693 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002694 return OutputTypeRange;
2695
2696 IntRange SubRange
2697 = GetExprRange(C, CE->getSubExpr(),
2698 std::min(MaxWidth, OutputTypeRange.Width));
2699
2700 // Bail out if the subexpr's range is as wide as the cast type.
2701 if (SubRange.Width >= OutputTypeRange.Width)
2702 return OutputTypeRange;
2703
2704 // Otherwise, we take the smaller width, and we're non-negative if
2705 // either the output type or the subexpr is.
2706 return IntRange(SubRange.Width,
2707 SubRange.NonNegative || OutputTypeRange.NonNegative);
2708 }
2709
2710 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2711 // If we can fold the condition, just take that operand.
2712 bool CondResult;
2713 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2714 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2715 : CO->getFalseExpr(),
2716 MaxWidth);
2717
2718 // Otherwise, conservatively merge.
2719 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2720 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2721 return IntRange::join(L, R);
2722 }
2723
2724 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2725 switch (BO->getOpcode()) {
2726
2727 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002728 case BO_LAnd:
2729 case BO_LOr:
2730 case BO_LT:
2731 case BO_GT:
2732 case BO_LE:
2733 case BO_GE:
2734 case BO_EQ:
2735 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002736 return IntRange::forBoolType();
2737
John McCall862ff872011-07-13 06:35:24 +00002738 // The type of the assignments is the type of the LHS, so the RHS
2739 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002740 case BO_MulAssign:
2741 case BO_DivAssign:
2742 case BO_RemAssign:
2743 case BO_AddAssign:
2744 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002745 case BO_XorAssign:
2746 case BO_OrAssign:
2747 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002748 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002749
John McCall862ff872011-07-13 06:35:24 +00002750 // Simple assignments just pass through the RHS, which will have
2751 // been coerced to the LHS type.
2752 case BO_Assign:
2753 // TODO: bitfields?
2754 return GetExprRange(C, BO->getRHS(), MaxWidth);
2755
John McCallf2370c92010-01-06 05:24:50 +00002756 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002757 case BO_PtrMemD:
2758 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002759 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002760
John McCall60fad452010-01-06 22:07:33 +00002761 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002762 case BO_And:
2763 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002764 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2765 GetExprRange(C, BO->getRHS(), MaxWidth));
2766
John McCallf2370c92010-01-06 05:24:50 +00002767 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002768 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002769 // ...except that we want to treat '1 << (blah)' as logically
2770 // positive. It's an important idiom.
2771 if (IntegerLiteral *I
2772 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2773 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002774 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002775 return IntRange(R.Width, /*NonNegative*/ true);
2776 }
2777 }
2778 // fallthrough
2779
John McCall2de56d12010-08-25 11:45:40 +00002780 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002781 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002782
John McCall60fad452010-01-06 22:07:33 +00002783 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002784 case BO_Shr:
2785 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002786 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2787
2788 // If the shift amount is a positive constant, drop the width by
2789 // that much.
2790 llvm::APSInt shift;
2791 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2792 shift.isNonNegative()) {
2793 unsigned zext = shift.getZExtValue();
2794 if (zext >= L.Width)
2795 L.Width = (L.NonNegative ? 0 : 1);
2796 else
2797 L.Width -= zext;
2798 }
2799
2800 return L;
2801 }
2802
2803 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002804 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002805 return GetExprRange(C, BO->getRHS(), MaxWidth);
2806
John McCall60fad452010-01-06 22:07:33 +00002807 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002808 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002809 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002810 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00002811 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002812
John McCall00fe7612011-07-14 22:39:48 +00002813 // The width of a division result is mostly determined by the size
2814 // of the LHS.
2815 case BO_Div: {
2816 // Don't 'pre-truncate' the operands.
2817 unsigned opWidth = C.getIntWidth(E->getType());
2818 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2819
2820 // If the divisor is constant, use that.
2821 llvm::APSInt divisor;
2822 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
2823 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
2824 if (log2 >= L.Width)
2825 L.Width = (L.NonNegative ? 0 : 1);
2826 else
2827 L.Width = std::min(L.Width - log2, MaxWidth);
2828 return L;
2829 }
2830
2831 // Otherwise, just use the LHS's width.
2832 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2833 return IntRange(L.Width, L.NonNegative && R.NonNegative);
2834 }
2835
2836 // The result of a remainder can't be larger than the result of
2837 // either side.
2838 case BO_Rem: {
2839 // Don't 'pre-truncate' the operands.
2840 unsigned opWidth = C.getIntWidth(E->getType());
2841 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2842 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2843
2844 IntRange meet = IntRange::meet(L, R);
2845 meet.Width = std::min(meet.Width, MaxWidth);
2846 return meet;
2847 }
2848
2849 // The default behavior is okay for these.
2850 case BO_Mul:
2851 case BO_Add:
2852 case BO_Xor:
2853 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00002854 break;
2855 }
2856
John McCall00fe7612011-07-14 22:39:48 +00002857 // The default case is to treat the operation as if it were closed
2858 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00002859 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2860 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2861 return IntRange::join(L, R);
2862 }
2863
2864 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2865 switch (UO->getOpcode()) {
2866 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002867 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002868 return IntRange::forBoolType();
2869
2870 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002871 case UO_Deref:
2872 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002873 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002874
2875 default:
2876 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2877 }
2878 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002879
2880 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002881 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002882 }
John McCallf2370c92010-01-06 05:24:50 +00002883
2884 FieldDecl *BitField = E->getBitField();
2885 if (BitField) {
2886 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2887 unsigned BitWidth = BitWidthAP.getZExtValue();
2888
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002889 return IntRange(BitWidth,
2890 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002891 }
2892
John McCall1844a6e2010-11-10 23:38:19 +00002893 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002894}
John McCall51313c32010-01-04 23:31:57 +00002895
John McCall323ed742010-05-06 08:58:33 +00002896IntRange GetExprRange(ASTContext &C, Expr *E) {
2897 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2898}
2899
John McCall51313c32010-01-04 23:31:57 +00002900/// Checks whether the given value, which currently has the given
2901/// source semantics, has the same value when coerced through the
2902/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002903bool IsSameFloatAfterCast(const llvm::APFloat &value,
2904 const llvm::fltSemantics &Src,
2905 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002906 llvm::APFloat truncated = value;
2907
2908 bool ignored;
2909 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2910 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2911
2912 return truncated.bitwiseIsEqual(value);
2913}
2914
2915/// Checks whether the given value, which currently has the given
2916/// source semantics, has the same value when coerced through the
2917/// target semantics.
2918///
2919/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002920bool IsSameFloatAfterCast(const APValue &value,
2921 const llvm::fltSemantics &Src,
2922 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002923 if (value.isFloat())
2924 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2925
2926 if (value.isVector()) {
2927 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2928 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2929 return false;
2930 return true;
2931 }
2932
2933 assert(value.isComplexFloat());
2934 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2935 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2936}
2937
John McCallb4eb64d2010-10-08 02:01:28 +00002938void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002939
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002940static bool IsZero(Sema &S, Expr *E) {
2941 // Suppress cases where we are comparing against an enum constant.
2942 if (const DeclRefExpr *DR =
2943 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2944 if (isa<EnumConstantDecl>(DR->getDecl()))
2945 return false;
2946
2947 // Suppress cases where the '0' value is expanded from a macro.
2948 if (E->getLocStart().isMacroID())
2949 return false;
2950
John McCall323ed742010-05-06 08:58:33 +00002951 llvm::APSInt Value;
2952 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2953}
2954
John McCall372e1032010-10-06 00:25:24 +00002955static bool HasEnumType(Expr *E) {
2956 // Strip off implicit integral promotions.
2957 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002958 if (ICE->getCastKind() != CK_IntegralCast &&
2959 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002960 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002961 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002962 }
2963
2964 return E->getType()->isEnumeralType();
2965}
2966
John McCall323ed742010-05-06 08:58:33 +00002967void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002968 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002969 if (E->isValueDependent())
2970 return;
2971
John McCall2de56d12010-08-25 11:45:40 +00002972 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002973 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002974 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002975 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002976 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002977 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002978 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002979 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002980 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002981 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002982 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002983 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002984 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002985 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002986 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002987 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2988 }
2989}
2990
2991/// Analyze the operands of the given comparison. Implements the
2992/// fallback case from AnalyzeComparison.
2993void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002994 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2995 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002996}
John McCall51313c32010-01-04 23:31:57 +00002997
John McCallba26e582010-01-04 23:21:16 +00002998/// \brief Implements -Wsign-compare.
2999///
3000/// \param lex the left-hand expression
3001/// \param rex the right-hand expression
3002/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00003003/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00003004void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3005 // The type the comparison is being performed in.
3006 QualType T = E->getLHS()->getType();
3007 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3008 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003009
John McCall323ed742010-05-06 08:58:33 +00003010 // We don't do anything special if this isn't an unsigned integral
3011 // comparison: we're only interested in integral comparisons, and
3012 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003013 //
3014 // We also don't care about value-dependent expressions or expressions
3015 // whose result is a constant.
3016 if (!T->hasUnsignedIntegerRepresentation()
3017 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003018 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003019
John McCall323ed742010-05-06 08:58:33 +00003020 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
3021 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003022
John McCall323ed742010-05-06 08:58:33 +00003023 // Check to see if one of the (unmodified) operands is of different
3024 // signedness.
3025 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00003026 if (lex->getType()->hasSignedIntegerRepresentation()) {
3027 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003028 "unsigned comparison between two signed integer expressions?");
3029 signedOperand = lex;
3030 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00003031 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00003032 signedOperand = rex;
3033 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00003034 } else {
John McCall323ed742010-05-06 08:58:33 +00003035 CheckTrivialUnsignedComparison(S, E);
3036 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003037 }
3038
John McCall323ed742010-05-06 08:58:33 +00003039 // Otherwise, calculate the effective range of the signed operand.
3040 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003041
John McCall323ed742010-05-06 08:58:33 +00003042 // Go ahead and analyze implicit conversions in the operands. Note
3043 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00003044 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
3045 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003046
John McCall323ed742010-05-06 08:58:33 +00003047 // If the signed range is non-negative, -Wsign-compare won't fire,
3048 // but we should still check for comparisons which are always true
3049 // or false.
3050 if (signedRange.NonNegative)
3051 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003052
3053 // For (in)equality comparisons, if the unsigned operand is a
3054 // constant which cannot collide with a overflowed signed operand,
3055 // then reinterpreting the signed operand as unsigned will not
3056 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003057 if (E->isEqualityOp()) {
3058 unsigned comparisonWidth = S.Context.getIntWidth(T);
3059 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003060
John McCall323ed742010-05-06 08:58:33 +00003061 // We should never be unable to prove that the unsigned operand is
3062 // non-negative.
3063 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3064
3065 if (unsignedRange.Width < comparisonWidth)
3066 return;
3067 }
3068
3069 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3070 << lex->getType() << rex->getType()
3071 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003072}
3073
John McCall15d7d122010-11-11 03:21:53 +00003074/// Analyzes an attempt to assign the given value to a bitfield.
3075///
3076/// Returns true if there was something fishy about the attempt.
3077bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3078 SourceLocation InitLoc) {
3079 assert(Bitfield->isBitField());
3080 if (Bitfield->isInvalidDecl())
3081 return false;
3082
John McCall91b60142010-11-11 05:33:51 +00003083 // White-list bool bitfields.
3084 if (Bitfield->getType()->isBooleanType())
3085 return false;
3086
Douglas Gregor46ff3032011-02-04 13:09:01 +00003087 // Ignore value- or type-dependent expressions.
3088 if (Bitfield->getBitWidth()->isValueDependent() ||
3089 Bitfield->getBitWidth()->isTypeDependent() ||
3090 Init->isValueDependent() ||
3091 Init->isTypeDependent())
3092 return false;
3093
John McCall15d7d122010-11-11 03:21:53 +00003094 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3095
3096 llvm::APSInt Width(32);
3097 Expr::EvalResult InitValue;
3098 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00003099 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003100 !InitValue.Val.isInt())
3101 return false;
3102
3103 const llvm::APSInt &Value = InitValue.Val.getInt();
3104 unsigned OriginalWidth = Value.getBitWidth();
3105 unsigned FieldWidth = Width.getZExtValue();
3106
3107 if (OriginalWidth <= FieldWidth)
3108 return false;
3109
Jay Foad9f71a8f2010-12-07 08:25:34 +00003110 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003111
3112 // It's fairly common to write values into signed bitfields
3113 // that, if sign-extended, would end up becoming a different
3114 // value. We don't want to warn about that.
3115 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003116 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003117 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003118 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003119
3120 if (Value == TruncatedValue)
3121 return false;
3122
3123 std::string PrettyValue = Value.toString(10);
3124 std::string PrettyTrunc = TruncatedValue.toString(10);
3125
3126 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3127 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3128 << Init->getSourceRange();
3129
3130 return true;
3131}
3132
John McCallbeb22aa2010-11-09 23:24:47 +00003133/// Analyze the given simple or compound assignment for warning-worthy
3134/// operations.
3135void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3136 // Just recurse on the LHS.
3137 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3138
3139 // We want to recurse on the RHS as normal unless we're assigning to
3140 // a bitfield.
3141 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003142 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3143 E->getOperatorLoc())) {
3144 // Recurse, ignoring any implicit conversions on the RHS.
3145 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3146 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003147 }
3148 }
3149
3150 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3151}
3152
John McCall51313c32010-01-04 23:31:57 +00003153/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003154void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3155 SourceLocation CContext, unsigned diag) {
3156 S.Diag(E->getExprLoc(), diag)
3157 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3158}
3159
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003160/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3161void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3162 unsigned diag) {
3163 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3164}
3165
Chandler Carruthf65076e2011-04-10 08:36:24 +00003166/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3167/// fixit hints when the cast wouldn't lose information to simply write the
3168/// expression with the expected type.
3169void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3170 SourceLocation CContext) {
3171 // Emit the primary warning first, then try to emit a fixit hint note if
3172 // reasonable.
3173 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3174 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3175
3176 const llvm::APFloat &Value = FL->getValue();
3177
3178 // Don't attempt to fix PPC double double literals.
3179 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3180 return;
3181
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003182 // Try to convert this exactly to an integer.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003183 bool isExact = false;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003184 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3185 T->hasUnsignedIntegerRepresentation());
3186 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003187 llvm::APFloat::rmTowardZero, &isExact)
3188 != llvm::APFloat::opOK || !isExact)
3189 return;
3190
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003191 std::string LiteralValue = IntegerValue.toString(10);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003192 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3193 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3194}
3195
John McCall091f23f2010-11-09 22:22:12 +00003196std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3197 if (!Range.Width) return "0";
3198
3199 llvm::APSInt ValueInRange = Value;
3200 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003201 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003202 return ValueInRange.toString(10);
3203}
3204
Ted Kremenekef9ff882011-03-10 20:03:42 +00003205static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3206 SourceManager &smgr = S.Context.getSourceManager();
3207 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3208}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003209
John McCall323ed742010-05-06 08:58:33 +00003210void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003211 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003212 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003213
John McCall323ed742010-05-06 08:58:33 +00003214 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3215 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3216 if (Source == Target) return;
3217 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003218
Chandler Carruth108f7562011-07-26 05:40:03 +00003219 // If the conversion context location is invalid don't complain. We also
3220 // don't want to emit a warning if the issue occurs from the expansion of
3221 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3222 // delay this check as long as possible. Once we detect we are in that
3223 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003224 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003225 return;
3226
John McCall51313c32010-01-04 23:31:57 +00003227 // Never diagnose implicit casts to bool.
3228 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3229 return;
3230
3231 // Strip vector types.
3232 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003233 if (!isa<VectorType>(Target)) {
3234 if (isFromSystemMacro(S, CC))
3235 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003236 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003237 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003238
3239 // If the vector cast is cast between two vectors of the same size, it is
3240 // a bitcast, not a conversion.
3241 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3242 return;
John McCall51313c32010-01-04 23:31:57 +00003243
3244 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3245 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3246 }
3247
3248 // Strip complex types.
3249 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003250 if (!isa<ComplexType>(Target)) {
3251 if (isFromSystemMacro(S, CC))
3252 return;
3253
John McCallb4eb64d2010-10-08 02:01:28 +00003254 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003255 }
John McCall51313c32010-01-04 23:31:57 +00003256
3257 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3258 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3259 }
3260
3261 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3262 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3263
3264 // If the source is floating point...
3265 if (SourceBT && SourceBT->isFloatingPoint()) {
3266 // ...and the target is floating point...
3267 if (TargetBT && TargetBT->isFloatingPoint()) {
3268 // ...then warn if we're dropping FP rank.
3269
3270 // Builtin FP kinds are ordered by increasing FP rank.
3271 if (SourceBT->getKind() > TargetBT->getKind()) {
3272 // Don't warn about float constants that are precisely
3273 // representable in the target type.
3274 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003275 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003276 // Value might be a float, a float vector, or a float complex.
3277 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003278 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3279 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003280 return;
3281 }
3282
Ted Kremenekef9ff882011-03-10 20:03:42 +00003283 if (isFromSystemMacro(S, CC))
3284 return;
3285
John McCallb4eb64d2010-10-08 02:01:28 +00003286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003287 }
3288 return;
3289 }
3290
Ted Kremenekef9ff882011-03-10 20:03:42 +00003291 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003292 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003293 if (isFromSystemMacro(S, CC))
3294 return;
3295
Chandler Carrutha5b93322011-02-17 11:05:49 +00003296 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003297 // We also want to warn on, e.g., "int i = -1.234"
3298 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3299 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3300 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3301
Chandler Carruthf65076e2011-04-10 08:36:24 +00003302 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3303 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003304 } else {
3305 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3306 }
3307 }
John McCall51313c32010-01-04 23:31:57 +00003308
3309 return;
3310 }
3311
John McCallf2370c92010-01-06 05:24:50 +00003312 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003313 return;
3314
Richard Trieu1838ca52011-05-29 19:59:02 +00003315 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3316 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3317 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3318 << E->getSourceRange() << clang::SourceRange(CC);
3319 return;
3320 }
3321
John McCall323ed742010-05-06 08:58:33 +00003322 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003323 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003324
3325 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003326 // If the source is a constant, use a default-on diagnostic.
3327 // TODO: this should happen for bitfield stores, too.
3328 llvm::APSInt Value(32);
3329 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003330 if (isFromSystemMacro(S, CC))
3331 return;
3332
John McCall091f23f2010-11-09 22:22:12 +00003333 std::string PrettySourceValue = Value.toString(10);
3334 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3335
3336 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3337 << PrettySourceValue << PrettyTargetValue
3338 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3339 return;
3340 }
3341
Chris Lattnerb792b302011-06-14 04:51:15 +00003342 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003343 if (isFromSystemMacro(S, CC))
3344 return;
3345
John McCallf2370c92010-01-06 05:24:50 +00003346 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003347 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3348 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003349 }
3350
3351 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3352 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3353 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003354
3355 if (isFromSystemMacro(S, CC))
3356 return;
3357
John McCall323ed742010-05-06 08:58:33 +00003358 unsigned DiagID = diag::warn_impcast_integer_sign;
3359
3360 // Traditionally, gcc has warned about this under -Wsign-compare.
3361 // We also want to warn about it in -Wconversion.
3362 // So if -Wconversion is off, use a completely identical diagnostic
3363 // in the sign-compare group.
3364 // The conditional-checking code will
3365 if (ICContext) {
3366 DiagID = diag::warn_impcast_integer_sign_conditional;
3367 *ICContext = true;
3368 }
3369
John McCallb4eb64d2010-10-08 02:01:28 +00003370 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003371 }
3372
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003373 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003374 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3375 // type, to give us better diagnostics.
3376 QualType SourceType = E->getType();
3377 if (!S.getLangOptions().CPlusPlus) {
3378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3379 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3380 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3381 SourceType = S.Context.getTypeDeclType(Enum);
3382 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3383 }
3384 }
3385
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003386 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3387 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3388 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003389 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003390 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003391 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003392 SourceEnum != TargetEnum) {
3393 if (isFromSystemMacro(S, CC))
3394 return;
3395
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003396 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003397 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003398 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003399
John McCall51313c32010-01-04 23:31:57 +00003400 return;
3401}
3402
John McCall323ed742010-05-06 08:58:33 +00003403void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3404
3405void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003406 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003407 E = E->IgnoreParenImpCasts();
3408
3409 if (isa<ConditionalOperator>(E))
3410 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3411
John McCallb4eb64d2010-10-08 02:01:28 +00003412 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003413 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003414 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003415 return;
3416}
3417
3418void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003419 SourceLocation CC = E->getQuestionLoc();
3420
3421 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003422
3423 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003424 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3425 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003426
3427 // If -Wconversion would have warned about either of the candidates
3428 // for a signedness conversion to the context type...
3429 if (!Suspicious) return;
3430
3431 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003432 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3433 CC))
John McCall323ed742010-05-06 08:58:33 +00003434 return;
3435
John McCall323ed742010-05-06 08:58:33 +00003436 // ...then check whether it would have warned about either of the
3437 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003438 if (E->getType() == T) return;
3439
3440 Suspicious = false;
3441 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3442 E->getType(), CC, &Suspicious);
3443 if (!Suspicious)
3444 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003445 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003446}
3447
3448/// AnalyzeImplicitConversions - Find and report any interesting
3449/// implicit conversions in the given expression. There are a couple
3450/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003451void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003452 QualType T = OrigE->getType();
3453 Expr *E = OrigE->IgnoreParenImpCasts();
3454
3455 // For conditional operators, we analyze the arguments as if they
3456 // were being fed directly into the output.
3457 if (isa<ConditionalOperator>(E)) {
3458 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3459 CheckConditionalOperator(S, CO, T);
3460 return;
3461 }
3462
3463 // Go ahead and check any implicit conversions we might have skipped.
3464 // The non-canonical typecheck is just an optimization;
3465 // CheckImplicitConversion will filter out dead implicit conversions.
3466 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003467 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003468
3469 // Now continue drilling into this expression.
3470
3471 // Skip past explicit casts.
3472 if (isa<ExplicitCastExpr>(E)) {
3473 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003474 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003475 }
3476
John McCallbeb22aa2010-11-09 23:24:47 +00003477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3478 // Do a somewhat different check with comparison operators.
3479 if (BO->isComparisonOp())
3480 return AnalyzeComparison(S, BO);
3481
3482 // And with assignments and compound assignments.
3483 if (BO->isAssignmentOp())
3484 return AnalyzeAssignment(S, BO);
3485 }
John McCall323ed742010-05-06 08:58:33 +00003486
3487 // These break the otherwise-useful invariant below. Fortunately,
3488 // we don't really need to recurse into them, because any internal
3489 // expressions should have been analyzed already when they were
3490 // built into statements.
3491 if (isa<StmtExpr>(E)) return;
3492
3493 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003494 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003495
3496 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003497 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003498 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003499 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003500}
3501
3502} // end anonymous namespace
3503
3504/// Diagnoses "dangerous" implicit conversions within the given
3505/// expression (which is a full expression). Implements -Wconversion
3506/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003507///
3508/// \param CC the "context" location of the implicit conversion, i.e.
3509/// the most location of the syntactic entity requiring the implicit
3510/// conversion
3511void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003512 // Don't diagnose in unevaluated contexts.
3513 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3514 return;
3515
3516 // Don't diagnose for value- or type-dependent expressions.
3517 if (E->isTypeDependent() || E->isValueDependent())
3518 return;
3519
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003520 // Check for array bounds violations in cases where the check isn't triggered
3521 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3522 // ArraySubscriptExpr is on the RHS of a variable initialization.
3523 CheckArrayAccess(E);
3524
John McCallb4eb64d2010-10-08 02:01:28 +00003525 // This is not the right CC for (e.g.) a variable initialization.
3526 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003527}
3528
John McCall15d7d122010-11-11 03:21:53 +00003529void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3530 FieldDecl *BitField,
3531 Expr *Init) {
3532 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3533}
3534
Mike Stumpf8c49212010-01-21 03:59:47 +00003535/// CheckParmsForFunctionDef - Check that the parameters of the given
3536/// function are appropriate for the definition of a function. This
3537/// takes care of any checks that cannot be performed on the
3538/// declaration itself, e.g., that the types of each of the function
3539/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003540bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3541 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003542 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003543 for (; P != PEnd; ++P) {
3544 ParmVarDecl *Param = *P;
3545
Mike Stumpf8c49212010-01-21 03:59:47 +00003546 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3547 // function declarator that is part of a function definition of
3548 // that function shall not have incomplete type.
3549 //
3550 // This is also C++ [dcl.fct]p6.
3551 if (!Param->isInvalidDecl() &&
3552 RequireCompleteType(Param->getLocation(), Param->getType(),
3553 diag::err_typecheck_decl_incomplete_type)) {
3554 Param->setInvalidDecl();
3555 HasInvalidParm = true;
3556 }
3557
3558 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3559 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003560 if (CheckParameterNames &&
3561 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003562 !Param->isImplicit() &&
3563 !getLangOptions().CPlusPlus)
3564 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003565
3566 // C99 6.7.5.3p12:
3567 // If the function declarator is not part of a definition of that
3568 // function, parameters may have incomplete type and may use the [*]
3569 // notation in their sequences of declarator specifiers to specify
3570 // variable length array types.
3571 QualType PType = Param->getOriginalType();
3572 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3573 if (AT->getSizeModifier() == ArrayType::Star) {
3574 // FIXME: This diagnosic should point the the '[*]' if source-location
3575 // information is added for it.
3576 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3577 }
3578 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003579 }
3580
3581 return HasInvalidParm;
3582}
John McCallb7f4ffe2010-08-12 21:44:57 +00003583
3584/// CheckCastAlign - Implements -Wcast-align, which warns when a
3585/// pointer cast increases the alignment requirements.
3586void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3587 // This is actually a lot of work to potentially be doing on every
3588 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003589 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3590 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003591 == Diagnostic::Ignored)
3592 return;
3593
3594 // Ignore dependent types.
3595 if (T->isDependentType() || Op->getType()->isDependentType())
3596 return;
3597
3598 // Require that the destination be a pointer type.
3599 const PointerType *DestPtr = T->getAs<PointerType>();
3600 if (!DestPtr) return;
3601
3602 // If the destination has alignment 1, we're done.
3603 QualType DestPointee = DestPtr->getPointeeType();
3604 if (DestPointee->isIncompleteType()) return;
3605 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3606 if (DestAlign.isOne()) return;
3607
3608 // Require that the source be a pointer type.
3609 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3610 if (!SrcPtr) return;
3611 QualType SrcPointee = SrcPtr->getPointeeType();
3612
3613 // Whitelist casts from cv void*. We already implicitly
3614 // whitelisted casts to cv void*, since they have alignment 1.
3615 // Also whitelist casts involving incomplete types, which implicitly
3616 // includes 'void'.
3617 if (SrcPointee->isIncompleteType()) return;
3618
3619 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3620 if (SrcAlign >= DestAlign) return;
3621
3622 Diag(TRange.getBegin(), diag::warn_cast_align)
3623 << Op->getType() << T
3624 << static_cast<unsigned>(SrcAlign.getQuantity())
3625 << static_cast<unsigned>(DestAlign.getQuantity())
3626 << TRange << Op->getSourceRange();
3627}
3628
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003629static const Type* getElementType(const Expr *BaseExpr) {
3630 const Type* EltType = BaseExpr->getType().getTypePtr();
3631 if (EltType->isAnyPointerType())
3632 return EltType->getPointeeType().getTypePtr();
3633 else if (EltType->isArrayType())
3634 return EltType->getBaseElementTypeUnsafe();
3635 return EltType;
3636}
3637
Chandler Carruthc2684342011-08-05 09:10:50 +00003638/// \brief Check whether this array fits the idiom of a size-one tail padded
3639/// array member of a struct.
3640///
3641/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3642/// commonly used to emulate flexible arrays in C89 code.
3643static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3644 const NamedDecl *ND) {
3645 if (Size != 1 || !ND) return false;
3646
3647 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3648 if (!FD) return false;
3649
3650 // Don't consider sizes resulting from macro expansions or template argument
3651 // substitution to form C89 tail-padded arrays.
3652 ConstantArrayTypeLoc TL =
3653 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3654 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3655 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3656 return false;
3657
3658 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3659 if (!RD || !RD->isStruct())
3660 return false;
3661
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003662 // See if this is the last field decl in the record.
3663 const Decl *D = FD;
3664 while ((D = D->getNextDeclInContext()))
3665 if (isa<FieldDecl>(D))
3666 return false;
3667 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003668}
3669
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003670void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3671 bool isSubscript, bool AllowOnePastEnd) {
3672 const Type* EffectiveType = getElementType(BaseExpr);
3673 BaseExpr = BaseExpr->IgnoreParenCasts();
3674 IndexExpr = IndexExpr->IgnoreParenCasts();
3675
Chandler Carruth34064582011-02-17 20:55:08 +00003676 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003677 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003678 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003679 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003680
Chandler Carruth34064582011-02-17 20:55:08 +00003681 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003682 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003683 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003684 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003685 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003686
Chandler Carruthba447122011-08-05 08:07:29 +00003687 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3689 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003690 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003691 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003692
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003693 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003694 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003695 if (!size.isStrictlyPositive())
3696 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003697
3698 const Type* BaseType = getElementType(BaseExpr);
3699 if (!isSubscript && BaseType != EffectiveType) {
3700 // Make sure we're comparing apples to apples when comparing index to size
3701 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3702 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003703 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003704 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003705 if (ptrarith_typesize != array_typesize) {
3706 // There's a cast to a different size type involved
3707 uint64_t ratio = array_typesize / ptrarith_typesize;
3708 // TODO: Be smarter about handling cases where array_typesize is not a
3709 // multiple of ptrarith_typesize
3710 if (ptrarith_typesize * ratio == array_typesize)
3711 size *= llvm::APInt(size.getBitWidth(), ratio);
3712 }
3713 }
3714
Chandler Carruth34064582011-02-17 20:55:08 +00003715 if (size.getBitWidth() > index.getBitWidth())
3716 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003717 else if (size.getBitWidth() < index.getBitWidth())
3718 size = size.sext(index.getBitWidth());
3719
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003720 // For array subscripting the index must be less than size, but for pointer
3721 // arithmetic also allow the index (offset) to be equal to size since
3722 // computing the next address after the end of the array is legal and
3723 // commonly done e.g. in C++ iterators and range-based for loops.
3724 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003725 return;
3726
3727 // Also don't warn for arrays of size 1 which are members of some
3728 // structure. These are often used to approximate flexible arrays in C89
3729 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003730 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003731 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003732
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003733 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3734 if (isSubscript)
3735 DiagID = diag::warn_array_index_exceeds_bounds;
3736
3737 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3738 PDiag(DiagID) << index.toString(10, true)
3739 << size.toString(10, true)
3740 << (unsigned)size.getLimitedValue(~0U)
3741 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003742 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003743 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3744 if (!isSubscript) {
3745 DiagID = diag::warn_ptr_arith_precedes_bounds;
3746 if (index.isNegative()) index = -index;
3747 }
3748
3749 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3750 PDiag(DiagID) << index.toString(10, true)
3751 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003752 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003753
Chandler Carruth35001ca2011-02-17 21:10:52 +00003754 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003755 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3756 PDiag(diag::note_array_index_out_of_bounds)
3757 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003758}
3759
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003760void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003761 int AllowOnePastEnd = 0;
3762 while (expr) {
3763 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003764 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003765 case Stmt::ArraySubscriptExprClass: {
3766 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3767 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3768 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003769 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003770 }
3771 case Stmt::UnaryOperatorClass: {
3772 // Only unwrap the * and & unary operators
3773 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3774 expr = UO->getSubExpr();
3775 switch (UO->getOpcode()) {
3776 case UO_AddrOf:
3777 AllowOnePastEnd++;
3778 break;
3779 case UO_Deref:
3780 AllowOnePastEnd--;
3781 break;
3782 default:
3783 return;
3784 }
3785 break;
3786 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003787 case Stmt::ConditionalOperatorClass: {
3788 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3789 if (const Expr *lhs = cond->getLHS())
3790 CheckArrayAccess(lhs);
3791 if (const Expr *rhs = cond->getRHS())
3792 CheckArrayAccess(rhs);
3793 return;
3794 }
3795 default:
3796 return;
3797 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003798 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003799}
John McCallf85e1932011-06-15 23:02:42 +00003800
3801//===--- CHECK: Objective-C retain cycles ----------------------------------//
3802
3803namespace {
3804 struct RetainCycleOwner {
3805 RetainCycleOwner() : Variable(0), Indirect(false) {}
3806 VarDecl *Variable;
3807 SourceRange Range;
3808 SourceLocation Loc;
3809 bool Indirect;
3810
3811 void setLocsFrom(Expr *e) {
3812 Loc = e->getExprLoc();
3813 Range = e->getSourceRange();
3814 }
3815 };
3816}
3817
3818/// Consider whether capturing the given variable can possibly lead to
3819/// a retain cycle.
3820static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3821 // In ARC, it's captured strongly iff the variable has __strong
3822 // lifetime. In MRR, it's captured strongly if the variable is
3823 // __block and has an appropriate type.
3824 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3825 return false;
3826
3827 owner.Variable = var;
3828 owner.setLocsFrom(ref);
3829 return true;
3830}
3831
3832static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3833 while (true) {
3834 e = e->IgnoreParens();
3835 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3836 switch (cast->getCastKind()) {
3837 case CK_BitCast:
3838 case CK_LValueBitCast:
3839 case CK_LValueToRValue:
John McCall7e5e5f42011-07-07 06:58:02 +00003840 case CK_ObjCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00003841 e = cast->getSubExpr();
3842 continue;
3843
3844 case CK_GetObjCProperty: {
3845 // Bail out if this isn't a strong explicit property.
3846 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3847 if (pre->isImplicitProperty()) return false;
3848 ObjCPropertyDecl *property = pre->getExplicitProperty();
3849 if (!(property->getPropertyAttributes() &
3850 (ObjCPropertyDecl::OBJC_PR_retain |
3851 ObjCPropertyDecl::OBJC_PR_copy |
3852 ObjCPropertyDecl::OBJC_PR_strong)) &&
3853 !(property->getPropertyIvarDecl() &&
3854 property->getPropertyIvarDecl()->getType()
3855 .getObjCLifetime() == Qualifiers::OCL_Strong))
3856 return false;
3857
3858 owner.Indirect = true;
3859 e = const_cast<Expr*>(pre->getBase());
3860 continue;
3861 }
3862
3863 default:
3864 return false;
3865 }
3866 }
3867
3868 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3869 ObjCIvarDecl *ivar = ref->getDecl();
3870 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3871 return false;
3872
3873 // Try to find a retain cycle in the base.
3874 if (!findRetainCycleOwner(ref->getBase(), owner))
3875 return false;
3876
3877 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3878 owner.Indirect = true;
3879 return true;
3880 }
3881
3882 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3883 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3884 if (!var) return false;
3885 return considerVariable(var, ref, owner);
3886 }
3887
3888 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3889 owner.Variable = ref->getDecl();
3890 owner.setLocsFrom(ref);
3891 return true;
3892 }
3893
3894 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3895 if (member->isArrow()) return false;
3896
3897 // Don't count this as an indirect ownership.
3898 e = member->getBase();
3899 continue;
3900 }
3901
3902 // Array ivars?
3903
3904 return false;
3905 }
3906}
3907
3908namespace {
3909 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3910 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3911 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3912 Variable(variable), Capturer(0) {}
3913
3914 VarDecl *Variable;
3915 Expr *Capturer;
3916
3917 void VisitDeclRefExpr(DeclRefExpr *ref) {
3918 if (ref->getDecl() == Variable && !Capturer)
3919 Capturer = ref;
3920 }
3921
3922 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3923 if (ref->getDecl() == Variable && !Capturer)
3924 Capturer = ref;
3925 }
3926
3927 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3928 if (Capturer) return;
3929 Visit(ref->getBase());
3930 if (Capturer && ref->isFreeIvar())
3931 Capturer = ref;
3932 }
3933
3934 void VisitBlockExpr(BlockExpr *block) {
3935 // Look inside nested blocks
3936 if (block->getBlockDecl()->capturesVariable(Variable))
3937 Visit(block->getBlockDecl()->getBody());
3938 }
3939 };
3940}
3941
3942/// Check whether the given argument is a block which captures a
3943/// variable.
3944static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3945 assert(owner.Variable && owner.Loc.isValid());
3946
3947 e = e->IgnoreParenCasts();
3948 BlockExpr *block = dyn_cast<BlockExpr>(e);
3949 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3950 return 0;
3951
3952 FindCaptureVisitor visitor(S.Context, owner.Variable);
3953 visitor.Visit(block->getBlockDecl()->getBody());
3954 return visitor.Capturer;
3955}
3956
3957static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3958 RetainCycleOwner &owner) {
3959 assert(capturer);
3960 assert(owner.Variable && owner.Loc.isValid());
3961
3962 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3963 << owner.Variable << capturer->getSourceRange();
3964 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3965 << owner.Indirect << owner.Range;
3966}
3967
3968/// Check for a keyword selector that starts with the word 'add' or
3969/// 'set'.
3970static bool isSetterLikeSelector(Selector sel) {
3971 if (sel.isUnarySelector()) return false;
3972
Chris Lattner5f9e2722011-07-23 10:55:15 +00003973 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00003974 while (!str.empty() && str.front() == '_') str = str.substr(1);
3975 if (str.startswith("set") || str.startswith("add"))
3976 str = str.substr(3);
3977 else
3978 return false;
3979
3980 if (str.empty()) return true;
3981 return !islower(str.front());
3982}
3983
3984/// Check a message send to see if it's likely to cause a retain cycle.
3985void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3986 // Only check instance methods whose selector looks like a setter.
3987 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3988 return;
3989
3990 // Try to find a variable that the receiver is strongly owned by.
3991 RetainCycleOwner owner;
3992 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3993 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3994 return;
3995 } else {
3996 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3997 owner.Variable = getCurMethodDecl()->getSelfDecl();
3998 owner.Loc = msg->getSuperLoc();
3999 owner.Range = msg->getSuperLoc();
4000 }
4001
4002 // Check whether the receiver is captured by any of the arguments.
4003 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4004 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4005 return diagnoseRetainCycle(*this, capturer, owner);
4006}
4007
4008/// Check a property assign to see if it's likely to cause a retain cycle.
4009void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4010 RetainCycleOwner owner;
4011 if (!findRetainCycleOwner(receiver, owner))
4012 return;
4013
4014 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4015 diagnoseRetainCycle(*this, capturer, owner);
4016}
4017
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004018bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004019 QualType LHS, Expr *RHS) {
4020 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4021 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004022 return false;
4023 // strip off any implicit cast added to get to the one arc-specific
4024 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4025 if (cast->getCastKind() == CK_ObjCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004026 Diag(Loc, diag::warn_arc_retained_assign)
4027 << (LT == Qualifiers::OCL_ExplicitNone)
4028 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004029 return true;
4030 }
4031 RHS = cast->getSubExpr();
4032 }
4033 return false;
John McCallf85e1932011-06-15 23:02:42 +00004034}
4035
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004036void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4037 Expr *LHS, Expr *RHS) {
4038 QualType LHSType = LHS->getType();
4039 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4040 return;
4041 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4042 // FIXME. Check for other life times.
4043 if (LT != Qualifiers::OCL_None)
4044 return;
4045
4046 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4047 if (PRE->isImplicitProperty())
4048 return;
4049 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4050 if (!PD)
4051 return;
4052
4053 unsigned Attributes = PD->getPropertyAttributes();
4054 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4055 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4056 if (cast->getCastKind() == CK_ObjCConsumeObject) {
4057 Diag(Loc, diag::warn_arc_retained_property_assign)
4058 << RHS->getSourceRange();
4059 return;
4060 }
4061 RHS = cast->getSubExpr();
4062 }
4063 }
4064}