blob: 1606e336ee7337e2d20f2d9921012c43adce84d3 [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"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000035#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000036#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000037#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000038#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000039#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000046 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000047}
48
John McCall8e10f3b2011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerouge77f68bb2011-09-09 22:41:49 +000069/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
70/// annotation is a non wide string literal.
71static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
72 Arg = Arg->IgnoreParenCasts();
73 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
74 if (!Literal || !Literal->isAscii()) {
75 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
76 << Arg->getSourceRange();
77 return true;
78 }
79 return false;
80}
81
John McCall60d7b3a2010-08-24 06:29:42 +000082ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000083Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000084 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000085
Chris Lattner946928f2010-10-01 23:23:24 +000086 // Find out if any arguments are required to be integer constant expressions.
87 unsigned ICEArguments = 0;
88 ASTContext::GetBuiltinTypeError Error;
89 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
90 if (Error != ASTContext::GE_None)
91 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
92
93 // If any arguments are required to be ICE's, check and diagnose.
94 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
95 // Skip arguments not required to be ICE's.
96 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
97
98 llvm::APSInt Result;
99 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
100 return true;
101 ICEArguments &= ~(1 << ArgNo);
102 }
103
Anders Carlssond406bf02009-08-16 01:56:34 +0000104 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000105 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000106 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000107 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000108 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000110 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000111 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000113 if (SemaBuiltinVAStart(TheCall))
114 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000115 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 case Builtin::BI__builtin_isgreater:
117 case Builtin::BI__builtin_isgreaterequal:
118 case Builtin::BI__builtin_isless:
119 case Builtin::BI__builtin_islessequal:
120 case Builtin::BI__builtin_islessgreater:
121 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinUnorderedCompare(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000125 case Builtin::BI__builtin_fpclassify:
126 if (SemaBuiltinFPClassification(TheCall, 6))
127 return ExprError();
128 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000129 case Builtin::BI__builtin_isfinite:
130 case Builtin::BI__builtin_isinf:
131 case Builtin::BI__builtin_isinf_sign:
132 case Builtin::BI__builtin_isnan:
133 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000134 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000135 return ExprError();
136 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000137 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 return SemaBuiltinShuffleVector(TheCall);
139 // TheCall will be freed by the smart pointer here, but that's fine, since
140 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000141 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000142 if (SemaBuiltinPrefetch(TheCall))
143 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000144 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000145 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinObjectSize(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000149 case Builtin::BI__builtin_longjmp:
150 if (SemaBuiltinLongjmp(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000153
154 case Builtin::BI__builtin_classify_type:
155 if (checkArgCount(*this, TheCall, 1)) return true;
156 TheCall->setType(Context.IntTy);
157 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000158 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000159 if (checkArgCount(*this, TheCall, 1)) return true;
160 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000161 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000162 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000163 case Builtin::BI__sync_fetch_and_add_1:
164 case Builtin::BI__sync_fetch_and_add_2:
165 case Builtin::BI__sync_fetch_and_add_4:
166 case Builtin::BI__sync_fetch_and_add_8:
167 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000168 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000169 case Builtin::BI__sync_fetch_and_sub_1:
170 case Builtin::BI__sync_fetch_and_sub_2:
171 case Builtin::BI__sync_fetch_and_sub_4:
172 case Builtin::BI__sync_fetch_and_sub_8:
173 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000174 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000175 case Builtin::BI__sync_fetch_and_or_1:
176 case Builtin::BI__sync_fetch_and_or_2:
177 case Builtin::BI__sync_fetch_and_or_4:
178 case Builtin::BI__sync_fetch_and_or_8:
179 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000180 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000181 case Builtin::BI__sync_fetch_and_and_1:
182 case Builtin::BI__sync_fetch_and_and_2:
183 case Builtin::BI__sync_fetch_and_and_4:
184 case Builtin::BI__sync_fetch_and_and_8:
185 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_xor_1:
188 case Builtin::BI__sync_fetch_and_xor_2:
189 case Builtin::BI__sync_fetch_and_xor_4:
190 case Builtin::BI__sync_fetch_and_xor_8:
191 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000192 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000193 case Builtin::BI__sync_add_and_fetch_1:
194 case Builtin::BI__sync_add_and_fetch_2:
195 case Builtin::BI__sync_add_and_fetch_4:
196 case Builtin::BI__sync_add_and_fetch_8:
197 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000198 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000199 case Builtin::BI__sync_sub_and_fetch_1:
200 case Builtin::BI__sync_sub_and_fetch_2:
201 case Builtin::BI__sync_sub_and_fetch_4:
202 case Builtin::BI__sync_sub_and_fetch_8:
203 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000204 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000205 case Builtin::BI__sync_and_and_fetch_1:
206 case Builtin::BI__sync_and_and_fetch_2:
207 case Builtin::BI__sync_and_and_fetch_4:
208 case Builtin::BI__sync_and_and_fetch_8:
209 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000210 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000211 case Builtin::BI__sync_or_and_fetch_1:
212 case Builtin::BI__sync_or_and_fetch_2:
213 case Builtin::BI__sync_or_and_fetch_4:
214 case Builtin::BI__sync_or_and_fetch_8:
215 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000216 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000217 case Builtin::BI__sync_xor_and_fetch_1:
218 case Builtin::BI__sync_xor_and_fetch_2:
219 case Builtin::BI__sync_xor_and_fetch_4:
220 case Builtin::BI__sync_xor_and_fetch_8:
221 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000222 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000223 case Builtin::BI__sync_val_compare_and_swap_1:
224 case Builtin::BI__sync_val_compare_and_swap_2:
225 case Builtin::BI__sync_val_compare_and_swap_4:
226 case Builtin::BI__sync_val_compare_and_swap_8:
227 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000228 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000229 case Builtin::BI__sync_bool_compare_and_swap_1:
230 case Builtin::BI__sync_bool_compare_and_swap_2:
231 case Builtin::BI__sync_bool_compare_and_swap_4:
232 case Builtin::BI__sync_bool_compare_and_swap_8:
233 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000234 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000235 case Builtin::BI__sync_lock_test_and_set_1:
236 case Builtin::BI__sync_lock_test_and_set_2:
237 case Builtin::BI__sync_lock_test_and_set_4:
238 case Builtin::BI__sync_lock_test_and_set_8:
239 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000240 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000241 case Builtin::BI__sync_lock_release_1:
242 case Builtin::BI__sync_lock_release_2:
243 case Builtin::BI__sync_lock_release_4:
244 case Builtin::BI__sync_lock_release_8:
245 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000246 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_swap_1:
248 case Builtin::BI__sync_swap_2:
249 case Builtin::BI__sync_swap_4:
250 case Builtin::BI__sync_swap_8:
251 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000252 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000253#define BUILTIN(ID, TYPE, ATTRS)
254#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
255 case Builtin::BI##ID: \
256 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
257#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000258 case Builtin::BI__builtin_annotation:
259 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
260 return ExprError();
261 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000262 }
263
264 // Since the target specific builtins for each arch overlap, only check those
265 // of the arch we are compiling for.
266 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000267 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000268 case llvm::Triple::arm:
269 case llvm::Triple::thumb:
270 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
271 return ExprError();
272 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000273 default:
274 break;
275 }
276 }
277
278 return move(TheCallResult);
279}
280
Nate Begeman61eecf52010-06-14 05:21:25 +0000281// Get the valid immediate range for the specified NEON type code.
282static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000283 NeonTypeFlags Type(t);
284 int IsQuad = Type.isQuad();
285 switch (Type.getEltType()) {
286 case NeonTypeFlags::Int8:
287 case NeonTypeFlags::Poly8:
288 return shift ? 7 : (8 << IsQuad) - 1;
289 case NeonTypeFlags::Int16:
290 case NeonTypeFlags::Poly16:
291 return shift ? 15 : (4 << IsQuad) - 1;
292 case NeonTypeFlags::Int32:
293 return shift ? 31 : (2 << IsQuad) - 1;
294 case NeonTypeFlags::Int64:
295 return shift ? 63 : (1 << IsQuad) - 1;
296 case NeonTypeFlags::Float16:
297 assert(!shift && "cannot shift float types!");
298 return (4 << IsQuad) - 1;
299 case NeonTypeFlags::Float32:
300 assert(!shift && "cannot shift float types!");
301 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000302 }
David Blaikie7530c032012-01-17 06:56:22 +0000303 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000304}
305
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000306/// getNeonEltType - Return the QualType corresponding to the elements of
307/// the vector type specified by the NeonTypeFlags. This is used to check
308/// the pointer arguments for Neon load/store intrinsics.
309static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
310 switch (Flags.getEltType()) {
311 case NeonTypeFlags::Int8:
312 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
313 case NeonTypeFlags::Int16:
314 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
315 case NeonTypeFlags::Int32:
316 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
317 case NeonTypeFlags::Int64:
318 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
319 case NeonTypeFlags::Poly8:
320 return Context.SignedCharTy;
321 case NeonTypeFlags::Poly16:
322 return Context.ShortTy;
323 case NeonTypeFlags::Float16:
324 return Context.UnsignedShortTy;
325 case NeonTypeFlags::Float32:
326 return Context.FloatTy;
327 }
David Blaikie7530c032012-01-17 06:56:22 +0000328 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000329}
330
Nate Begeman26a31422010-06-08 02:47:44 +0000331bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000332 llvm::APSInt Result;
333
Nate Begeman0d15c532010-06-13 04:47:52 +0000334 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000335 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000336 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000337 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000338 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000339#define GET_NEON_OVERLOAD_CHECK
340#include "clang/Basic/arm_neon.inc"
341#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000342 }
343
Nate Begeman0d15c532010-06-13 04:47:52 +0000344 // For NEON intrinsics which are overloaded on vector element type, validate
345 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000346 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000347 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000348 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000349 return true;
350
Bob Wilsonda95f732011-11-08 01:16:11 +0000351 TV = Result.getLimitedValue(64);
352 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000353 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000354 << TheCall->getArg(ImmArg)->getSourceRange();
355 }
356
Bob Wilson46482552011-11-16 21:32:23 +0000357 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000358 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000359 Expr *Arg = TheCall->getArg(PtrArgNum);
360 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
361 Arg = ICE->getSubExpr();
362 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
363 QualType RHSTy = RHS.get()->getType();
364 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
365 if (HasConstPtr)
366 EltTy = EltTy.withConst();
367 QualType LHSTy = Context.getPointerType(EltTy);
368 AssignConvertType ConvTy;
369 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
370 if (RHS.isInvalid())
371 return true;
372 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
373 RHS.get(), AA_Assigning))
374 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000375 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000376
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 // For NEON intrinsics which take an immediate value as part of the
378 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000379 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000380 switch (BuiltinID) {
381 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000382 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
383 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000384 case ARM::BI__builtin_arm_vcvtr_f:
385 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000386#define GET_NEON_IMMEDIATE_CHECK
387#include "clang/Basic/arm_neon.inc"
388#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000389 };
390
Nate Begeman61eecf52010-06-14 05:21:25 +0000391 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 if (SemaBuiltinConstantArg(TheCall, i, Result))
393 return true;
394
Nate Begeman61eecf52010-06-14 05:21:25 +0000395 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000397 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000398 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000399 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000400
Nate Begeman99c40bb2010-08-03 21:32:34 +0000401 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000402 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000403}
Daniel Dunbarde454282008-10-02 18:44:07 +0000404
Anders Carlssond406bf02009-08-16 01:56:34 +0000405/// CheckFunctionCall - Check a direct function call for various correctness
406/// and safety properties not strictly enforced by the C type system.
407bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
408 // Get the IdentifierInfo* for the called function.
409 IdentifierInfo *FnInfo = FDecl->getIdentifier();
410
411 // None of the checks below are needed for functions that don't have
412 // simple names (e.g., C++ conversion functions).
413 if (!FnInfo)
414 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Daniel Dunbarde454282008-10-02 18:44:07 +0000416 // FIXME: This mechanism should be abstracted to be less fragile and
417 // more efficient. For example, just map function ids to custom
418 // handlers.
419
Ted Kremenekc82faca2010-09-09 04:33:05 +0000420 // Printf and scanf checking.
421 for (specific_attr_iterator<FormatAttr>
422 i = FDecl->specific_attr_begin<FormatAttr>(),
423 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000424 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000425 }
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Ted Kremenekc82faca2010-09-09 04:33:05 +0000427 for (specific_attr_iterator<NonNullAttr>
428 i = FDecl->specific_attr_begin<NonNullAttr>(),
429 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000430 CheckNonNullArguments(*i, TheCall->getArgs(),
431 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000432 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000433
Anna Zaks0a151a12012-01-17 00:37:07 +0000434 unsigned CMId = FDecl->getMemoryFunctionKind();
435 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000436 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000437
Anna Zaksd9b859a2012-01-13 21:52:01 +0000438 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000439 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000440 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000441 else if (CMId == Builtin::BIstrncat)
442 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000443 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000444 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000445
Anders Carlssond406bf02009-08-16 01:56:34 +0000446 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000447}
448
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000449bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
450 Expr **Args, unsigned NumArgs) {
451 for (specific_attr_iterator<FormatAttr>
452 i = Method->specific_attr_begin<FormatAttr>(),
453 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
454
455 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
456 Method->getSourceRange());
457 }
458
459 // diagnose nonnull arguments.
460 for (specific_attr_iterator<NonNullAttr>
461 i = Method->specific_attr_begin<NonNullAttr>(),
462 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
463 CheckNonNullArguments(*i, Args, lbrac);
464 }
465
466 return false;
467}
468
Anders Carlssond406bf02009-08-16 01:56:34 +0000469bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000470 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
471 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000472 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000474 QualType Ty = V->getType();
475 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000476 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000478 // format string checking.
479 for (specific_attr_iterator<FormatAttr>
480 i = NDecl->specific_attr_begin<FormatAttr>(),
481 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
482 CheckFormatArguments(*i, TheCall);
483 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000484
485 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000486}
487
Richard Smithff34d402012-04-12 05:08:17 +0000488ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
489 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000490 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
491 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000492
Richard Smithff34d402012-04-12 05:08:17 +0000493 // All these operations take one of the following forms:
494 enum {
495 // C __c11_atomic_init(A *, C)
496 Init,
497 // C __c11_atomic_load(A *, int)
498 Load,
499 // void __atomic_load(A *, CP, int)
500 Copy,
501 // C __c11_atomic_add(A *, M, int)
502 Arithmetic,
503 // C __atomic_exchange_n(A *, CP, int)
504 Xchg,
505 // void __atomic_exchange(A *, C *, CP, int)
506 GNUXchg,
507 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
508 C11CmpXchg,
509 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
510 GNUCmpXchg
511 } Form = Init;
512 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
513 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
514 // where:
515 // C is an appropriate type,
516 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
517 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
518 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
519 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000520
Richard Smithff34d402012-04-12 05:08:17 +0000521 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
522 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
523 && "need to update code for modified C11 atomics");
524 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
525 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
526 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
527 Op == AtomicExpr::AO__atomic_store_n ||
528 Op == AtomicExpr::AO__atomic_exchange_n ||
529 Op == AtomicExpr::AO__atomic_compare_exchange_n;
530 bool IsAddSub = false;
531
532 switch (Op) {
533 case AtomicExpr::AO__c11_atomic_init:
534 Form = Init;
535 break;
536
537 case AtomicExpr::AO__c11_atomic_load:
538 case AtomicExpr::AO__atomic_load_n:
539 Form = Load;
540 break;
541
542 case AtomicExpr::AO__c11_atomic_store:
543 case AtomicExpr::AO__atomic_load:
544 case AtomicExpr::AO__atomic_store:
545 case AtomicExpr::AO__atomic_store_n:
546 Form = Copy;
547 break;
548
549 case AtomicExpr::AO__c11_atomic_fetch_add:
550 case AtomicExpr::AO__c11_atomic_fetch_sub:
551 case AtomicExpr::AO__atomic_fetch_add:
552 case AtomicExpr::AO__atomic_fetch_sub:
553 case AtomicExpr::AO__atomic_add_fetch:
554 case AtomicExpr::AO__atomic_sub_fetch:
555 IsAddSub = true;
556 // Fall through.
557 case AtomicExpr::AO__c11_atomic_fetch_and:
558 case AtomicExpr::AO__c11_atomic_fetch_or:
559 case AtomicExpr::AO__c11_atomic_fetch_xor:
560 case AtomicExpr::AO__atomic_fetch_and:
561 case AtomicExpr::AO__atomic_fetch_or:
562 case AtomicExpr::AO__atomic_fetch_xor:
563 case AtomicExpr::AO__atomic_and_fetch:
564 case AtomicExpr::AO__atomic_or_fetch:
565 case AtomicExpr::AO__atomic_xor_fetch:
566 Form = Arithmetic;
567 break;
568
569 case AtomicExpr::AO__c11_atomic_exchange:
570 case AtomicExpr::AO__atomic_exchange_n:
571 Form = Xchg;
572 break;
573
574 case AtomicExpr::AO__atomic_exchange:
575 Form = GNUXchg;
576 break;
577
578 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
579 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
580 Form = C11CmpXchg;
581 break;
582
583 case AtomicExpr::AO__atomic_compare_exchange:
584 case AtomicExpr::AO__atomic_compare_exchange_n:
585 Form = GNUCmpXchg;
586 break;
587 }
588
589 // Check we have the right number of arguments.
590 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000591 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000592 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000593 << TheCall->getCallee()->getSourceRange();
594 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000595 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
596 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000597 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000598 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000599 << TheCall->getCallee()->getSourceRange();
600 return ExprError();
601 }
602
Richard Smithff34d402012-04-12 05:08:17 +0000603 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000604 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000605 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
606 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
607 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000608 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000609 << Ptr->getType() << Ptr->getSourceRange();
610 return ExprError();
611 }
612
Richard Smithff34d402012-04-12 05:08:17 +0000613 // For a __c11 builtin, this should be a pointer to an _Atomic type.
614 QualType AtomTy = pointerType->getPointeeType(); // 'A'
615 QualType ValType = AtomTy; // 'C'
616 if (IsC11) {
617 if (!AtomTy->isAtomicType()) {
618 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
619 << Ptr->getType() << Ptr->getSourceRange();
620 return ExprError();
621 }
622 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000623 }
Eli Friedman276b0612011-10-11 02:20:01 +0000624
Richard Smithff34d402012-04-12 05:08:17 +0000625 // For an arithmetic operation, the implied arithmetic must be well-formed.
626 if (Form == Arithmetic) {
627 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
628 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
629 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
630 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
631 return ExprError();
632 }
633 if (!IsAddSub && !ValType->isIntegerType()) {
634 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
635 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
636 return ExprError();
637 }
638 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
639 // For __atomic_*_n operations, the value type must be a scalar integral or
640 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000641 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000642 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
643 return ExprError();
644 }
645
646 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
647 // For GNU atomics, require a trivially-copyable type. This is not part of
648 // the GNU atomics specification, but we enforce it for sanity.
649 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000650 << Ptr->getType() << Ptr->getSourceRange();
651 return ExprError();
652 }
653
Richard Smithff34d402012-04-12 05:08:17 +0000654 // FIXME: For any builtin other than a load, the ValType must not be
655 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000656
657 switch (ValType.getObjCLifetime()) {
658 case Qualifiers::OCL_None:
659 case Qualifiers::OCL_ExplicitNone:
660 // okay
661 break;
662
663 case Qualifiers::OCL_Weak:
664 case Qualifiers::OCL_Strong:
665 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000666 // FIXME: Can this happen? By this point, ValType should be known
667 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000668 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
669 << ValType << Ptr->getSourceRange();
670 return ExprError();
671 }
672
673 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000674 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000675 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000676 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000677 ResultType = Context.BoolTy;
678
Richard Smithff34d402012-04-12 05:08:17 +0000679 // The type of a parameter passed 'by value'. In the GNU atomics, such
680 // arguments are actually passed as pointers.
681 QualType ByValType = ValType; // 'CP'
682 if (!IsC11 && !IsN)
683 ByValType = Ptr->getType();
684
Eli Friedman276b0612011-10-11 02:20:01 +0000685 // The first argument --- the pointer --- has a fixed type; we
686 // deduce the types of the rest of the arguments accordingly. Walk
687 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000688 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000689 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000690 if (i < NumVals[Form] + 1) {
691 switch (i) {
692 case 1:
693 // The second argument is the non-atomic operand. For arithmetic, this
694 // is always passed by value, and for a compare_exchange it is always
695 // passed by address. For the rest, GNU uses by-address and C11 uses
696 // by-value.
697 assert(Form != Load);
698 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
699 Ty = ValType;
700 else if (Form == Copy || Form == Xchg)
701 Ty = ByValType;
702 else if (Form == Arithmetic)
703 Ty = Context.getPointerDiffType();
704 else
705 Ty = Context.getPointerType(ValType.getUnqualifiedType());
706 break;
707 case 2:
708 // The third argument to compare_exchange / GNU exchange is a
709 // (pointer to a) desired value.
710 Ty = ByValType;
711 break;
712 case 3:
713 // The fourth argument to GNU compare_exchange is a 'weak' flag.
714 Ty = Context.BoolTy;
715 break;
716 }
Eli Friedman276b0612011-10-11 02:20:01 +0000717 } else {
718 // The order(s) are always converted to int.
719 Ty = Context.IntTy;
720 }
Richard Smithff34d402012-04-12 05:08:17 +0000721
Eli Friedman276b0612011-10-11 02:20:01 +0000722 InitializedEntity Entity =
723 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000724 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000725 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
726 if (Arg.isInvalid())
727 return true;
728 TheCall->setArg(i, Arg.get());
729 }
730
Richard Smithff34d402012-04-12 05:08:17 +0000731 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000732 SmallVector<Expr*, 5> SubExprs;
733 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000734 switch (Form) {
735 case Init:
736 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000737 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000738 break;
739 case Load:
740 SubExprs.push_back(TheCall->getArg(1)); // Order
741 break;
742 case Copy:
743 case Arithmetic:
744 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000745 SubExprs.push_back(TheCall->getArg(2)); // Order
746 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000747 break;
748 case GNUXchg:
749 // Note, AtomicExpr::getVal2() has a special case for this atomic.
750 SubExprs.push_back(TheCall->getArg(3)); // Order
751 SubExprs.push_back(TheCall->getArg(1)); // Val1
752 SubExprs.push_back(TheCall->getArg(2)); // Val2
753 break;
754 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000755 SubExprs.push_back(TheCall->getArg(3)); // Order
756 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000757 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000758 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000759 break;
760 case GNUCmpXchg:
761 SubExprs.push_back(TheCall->getArg(4)); // Order
762 SubExprs.push_back(TheCall->getArg(1)); // Val1
763 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
764 SubExprs.push_back(TheCall->getArg(2)); // Val2
765 SubExprs.push_back(TheCall->getArg(3)); // Weak
766 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000767 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000768
769 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
770 SubExprs.data(), SubExprs.size(),
771 ResultType, Op,
772 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000773}
774
775
John McCall5f8d6042011-08-27 01:09:30 +0000776/// checkBuiltinArgument - Given a call to a builtin function, perform
777/// normal type-checking on the given argument, updating the call in
778/// place. This is useful when a builtin function requires custom
779/// type-checking for some of its arguments but not necessarily all of
780/// them.
781///
782/// Returns true on error.
783static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
784 FunctionDecl *Fn = E->getDirectCallee();
785 assert(Fn && "builtin call without direct callee!");
786
787 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
788 InitializedEntity Entity =
789 InitializedEntity::InitializeParameter(S.Context, Param);
790
791 ExprResult Arg = E->getArg(0);
792 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
793 if (Arg.isInvalid())
794 return true;
795
796 E->setArg(ArgIndex, Arg.take());
797 return false;
798}
799
Chris Lattner5caa3702009-05-08 06:58:22 +0000800/// SemaBuiltinAtomicOverloaded - We have a call to a function like
801/// __sync_fetch_and_add, which is an overloaded function based on the pointer
802/// type of its first argument. The main ActOnCallExpr routines have already
803/// promoted the types of arguments because all of these calls are prototyped as
804/// void(...).
805///
806/// This function goes through and does final semantic checking for these
807/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000808ExprResult
809Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000810 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000811 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
812 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
813
814 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000815 if (TheCall->getNumArgs() < 1) {
816 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
817 << 0 << 1 << TheCall->getNumArgs()
818 << TheCall->getCallee()->getSourceRange();
819 return ExprError();
820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Chris Lattner5caa3702009-05-08 06:58:22 +0000822 // Inspect the first argument of the atomic builtin. This should always be
823 // a pointer type, whose element is an integral scalar or pointer type.
824 // Because it is a pointer type, we don't have to worry about any implicit
825 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000826 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000827 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000828 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
829 if (FirstArgResult.isInvalid())
830 return ExprError();
831 FirstArg = FirstArgResult.take();
832 TheCall->setArg(0, FirstArg);
833
John McCallf85e1932011-06-15 23:02:42 +0000834 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
835 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000836 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
837 << FirstArg->getType() << FirstArg->getSourceRange();
838 return ExprError();
839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
John McCallf85e1932011-06-15 23:02:42 +0000841 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000842 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000843 !ValType->isBlockPointerType()) {
844 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
845 << FirstArg->getType() << FirstArg->getSourceRange();
846 return ExprError();
847 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000848
John McCallf85e1932011-06-15 23:02:42 +0000849 switch (ValType.getObjCLifetime()) {
850 case Qualifiers::OCL_None:
851 case Qualifiers::OCL_ExplicitNone:
852 // okay
853 break;
854
855 case Qualifiers::OCL_Weak:
856 case Qualifiers::OCL_Strong:
857 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000858 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000859 << ValType << FirstArg->getSourceRange();
860 return ExprError();
861 }
862
John McCallb45ae252011-10-05 07:41:44 +0000863 // Strip any qualifiers off ValType.
864 ValType = ValType.getUnqualifiedType();
865
Chandler Carruth8d13d222010-07-18 20:54:12 +0000866 // The majority of builtins return a value, but a few have special return
867 // types, so allow them to override appropriately below.
868 QualType ResultType = ValType;
869
Chris Lattner5caa3702009-05-08 06:58:22 +0000870 // We need to figure out which concrete builtin this maps onto. For example,
871 // __sync_fetch_and_add with a 2 byte object turns into
872 // __sync_fetch_and_add_2.
873#define BUILTIN_ROW(x) \
874 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
875 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Chris Lattner5caa3702009-05-08 06:58:22 +0000877 static const unsigned BuiltinIndices[][5] = {
878 BUILTIN_ROW(__sync_fetch_and_add),
879 BUILTIN_ROW(__sync_fetch_and_sub),
880 BUILTIN_ROW(__sync_fetch_and_or),
881 BUILTIN_ROW(__sync_fetch_and_and),
882 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner5caa3702009-05-08 06:58:22 +0000884 BUILTIN_ROW(__sync_add_and_fetch),
885 BUILTIN_ROW(__sync_sub_and_fetch),
886 BUILTIN_ROW(__sync_and_and_fetch),
887 BUILTIN_ROW(__sync_or_and_fetch),
888 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner5caa3702009-05-08 06:58:22 +0000890 BUILTIN_ROW(__sync_val_compare_and_swap),
891 BUILTIN_ROW(__sync_bool_compare_and_swap),
892 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000893 BUILTIN_ROW(__sync_lock_release),
894 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 };
Mike Stump1eb44332009-09-09 15:08:12 +0000896#undef BUILTIN_ROW
897
Chris Lattner5caa3702009-05-08 06:58:22 +0000898 // Determine the index of the size.
899 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000900 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000901 case 1: SizeIndex = 0; break;
902 case 2: SizeIndex = 1; break;
903 case 4: SizeIndex = 2; break;
904 case 8: SizeIndex = 3; break;
905 case 16: SizeIndex = 4; break;
906 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000907 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
908 << FirstArg->getType() << FirstArg->getSourceRange();
909 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattner5caa3702009-05-08 06:58:22 +0000912 // Each of these builtins has one pointer argument, followed by some number of
913 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
914 // that we ignore. Find out which row of BuiltinIndices to read from as well
915 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000916 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000917 unsigned BuiltinIndex, NumFixed = 1;
918 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000919 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000920 case Builtin::BI__sync_fetch_and_add:
921 case Builtin::BI__sync_fetch_and_add_1:
922 case Builtin::BI__sync_fetch_and_add_2:
923 case Builtin::BI__sync_fetch_and_add_4:
924 case Builtin::BI__sync_fetch_and_add_8:
925 case Builtin::BI__sync_fetch_and_add_16:
926 BuiltinIndex = 0;
927 break;
928
929 case Builtin::BI__sync_fetch_and_sub:
930 case Builtin::BI__sync_fetch_and_sub_1:
931 case Builtin::BI__sync_fetch_and_sub_2:
932 case Builtin::BI__sync_fetch_and_sub_4:
933 case Builtin::BI__sync_fetch_and_sub_8:
934 case Builtin::BI__sync_fetch_and_sub_16:
935 BuiltinIndex = 1;
936 break;
937
938 case Builtin::BI__sync_fetch_and_or:
939 case Builtin::BI__sync_fetch_and_or_1:
940 case Builtin::BI__sync_fetch_and_or_2:
941 case Builtin::BI__sync_fetch_and_or_4:
942 case Builtin::BI__sync_fetch_and_or_8:
943 case Builtin::BI__sync_fetch_and_or_16:
944 BuiltinIndex = 2;
945 break;
946
947 case Builtin::BI__sync_fetch_and_and:
948 case Builtin::BI__sync_fetch_and_and_1:
949 case Builtin::BI__sync_fetch_and_and_2:
950 case Builtin::BI__sync_fetch_and_and_4:
951 case Builtin::BI__sync_fetch_and_and_8:
952 case Builtin::BI__sync_fetch_and_and_16:
953 BuiltinIndex = 3;
954 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregora9766412011-11-28 16:30:08 +0000956 case Builtin::BI__sync_fetch_and_xor:
957 case Builtin::BI__sync_fetch_and_xor_1:
958 case Builtin::BI__sync_fetch_and_xor_2:
959 case Builtin::BI__sync_fetch_and_xor_4:
960 case Builtin::BI__sync_fetch_and_xor_8:
961 case Builtin::BI__sync_fetch_and_xor_16:
962 BuiltinIndex = 4;
963 break;
964
965 case Builtin::BI__sync_add_and_fetch:
966 case Builtin::BI__sync_add_and_fetch_1:
967 case Builtin::BI__sync_add_and_fetch_2:
968 case Builtin::BI__sync_add_and_fetch_4:
969 case Builtin::BI__sync_add_and_fetch_8:
970 case Builtin::BI__sync_add_and_fetch_16:
971 BuiltinIndex = 5;
972 break;
973
974 case Builtin::BI__sync_sub_and_fetch:
975 case Builtin::BI__sync_sub_and_fetch_1:
976 case Builtin::BI__sync_sub_and_fetch_2:
977 case Builtin::BI__sync_sub_and_fetch_4:
978 case Builtin::BI__sync_sub_and_fetch_8:
979 case Builtin::BI__sync_sub_and_fetch_16:
980 BuiltinIndex = 6;
981 break;
982
983 case Builtin::BI__sync_and_and_fetch:
984 case Builtin::BI__sync_and_and_fetch_1:
985 case Builtin::BI__sync_and_and_fetch_2:
986 case Builtin::BI__sync_and_and_fetch_4:
987 case Builtin::BI__sync_and_and_fetch_8:
988 case Builtin::BI__sync_and_and_fetch_16:
989 BuiltinIndex = 7;
990 break;
991
992 case Builtin::BI__sync_or_and_fetch:
993 case Builtin::BI__sync_or_and_fetch_1:
994 case Builtin::BI__sync_or_and_fetch_2:
995 case Builtin::BI__sync_or_and_fetch_4:
996 case Builtin::BI__sync_or_and_fetch_8:
997 case Builtin::BI__sync_or_and_fetch_16:
998 BuiltinIndex = 8;
999 break;
1000
1001 case Builtin::BI__sync_xor_and_fetch:
1002 case Builtin::BI__sync_xor_and_fetch_1:
1003 case Builtin::BI__sync_xor_and_fetch_2:
1004 case Builtin::BI__sync_xor_and_fetch_4:
1005 case Builtin::BI__sync_xor_and_fetch_8:
1006 case Builtin::BI__sync_xor_and_fetch_16:
1007 BuiltinIndex = 9;
1008 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner5caa3702009-05-08 06:58:22 +00001010 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001011 case Builtin::BI__sync_val_compare_and_swap_1:
1012 case Builtin::BI__sync_val_compare_and_swap_2:
1013 case Builtin::BI__sync_val_compare_and_swap_4:
1014 case Builtin::BI__sync_val_compare_and_swap_8:
1015 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001016 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001017 NumFixed = 2;
1018 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001019
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001021 case Builtin::BI__sync_bool_compare_and_swap_1:
1022 case Builtin::BI__sync_bool_compare_and_swap_2:
1023 case Builtin::BI__sync_bool_compare_and_swap_4:
1024 case Builtin::BI__sync_bool_compare_and_swap_8:
1025 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001026 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001028 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001029 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001030
1031 case Builtin::BI__sync_lock_test_and_set:
1032 case Builtin::BI__sync_lock_test_and_set_1:
1033 case Builtin::BI__sync_lock_test_and_set_2:
1034 case Builtin::BI__sync_lock_test_and_set_4:
1035 case Builtin::BI__sync_lock_test_and_set_8:
1036 case Builtin::BI__sync_lock_test_and_set_16:
1037 BuiltinIndex = 12;
1038 break;
1039
Chris Lattner5caa3702009-05-08 06:58:22 +00001040 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001041 case Builtin::BI__sync_lock_release_1:
1042 case Builtin::BI__sync_lock_release_2:
1043 case Builtin::BI__sync_lock_release_4:
1044 case Builtin::BI__sync_lock_release_8:
1045 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001046 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001047 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001048 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001049 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001050
1051 case Builtin::BI__sync_swap:
1052 case Builtin::BI__sync_swap_1:
1053 case Builtin::BI__sync_swap_2:
1054 case Builtin::BI__sync_swap_4:
1055 case Builtin::BI__sync_swap_8:
1056 case Builtin::BI__sync_swap_16:
1057 BuiltinIndex = 14;
1058 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001059 }
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Chris Lattner5caa3702009-05-08 06:58:22 +00001061 // Now that we know how many fixed arguments we expect, first check that we
1062 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001063 if (TheCall->getNumArgs() < 1+NumFixed) {
1064 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1065 << 0 << 1+NumFixed << TheCall->getNumArgs()
1066 << TheCall->getCallee()->getSourceRange();
1067 return ExprError();
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001070 // Get the decl for the concrete builtin from this, we can tell what the
1071 // concrete integer type we should convert to is.
1072 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1073 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1074 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001075 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001076 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1077 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001078
John McCallf871d0c2010-08-07 06:22:56 +00001079 // The first argument --- the pointer --- has a fixed type; we
1080 // deduce the types of the rest of the arguments accordingly. Walk
1081 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001082 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001083 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner5caa3702009-05-08 06:58:22 +00001085 // GCC does an implicit conversion to the pointer or integer ValType. This
1086 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001087 // Initialize the argument.
1088 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1089 ValType, /*consume*/ false);
1090 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001091 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001092 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Chris Lattner5caa3702009-05-08 06:58:22 +00001094 // Okay, we have something that *can* be converted to the right type. Check
1095 // to see if there is a potentially weird extension going on here. This can
1096 // happen when you do an atomic operation on something like an char* and
1097 // pass in 42. The 42 gets converted to char. This is even more strange
1098 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001099 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001100 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001103 ASTContext& Context = this->getASTContext();
1104
1105 // Create a new DeclRefExpr to refer to the new decl.
1106 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1107 Context,
1108 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001109 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001110 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001111 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001112 DRE->getLocation(),
1113 NewBuiltinDecl->getType(),
1114 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Chris Lattner5caa3702009-05-08 06:58:22 +00001116 // Set the callee in the CallExpr.
1117 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001118 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001119 if (PromotedCall.isInvalid())
1120 return ExprError();
1121 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001123 // Change the result type of the call to match the original value type. This
1124 // is arbitrary, but the codegen for these builtins ins design to handle it
1125 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001126 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001127
1128 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001129}
1130
Chris Lattner69039812009-02-18 06:01:06 +00001131/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001132/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001133/// Note: It might also make sense to do the UTF-16 conversion here (would
1134/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001135bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001136 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001137 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1138
Douglas Gregor5cee1192011-07-27 05:40:30 +00001139 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001140 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1141 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001142 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001145 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001146 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001147 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001148 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001149 const UTF8 *FromPtr = (UTF8 *)String.data();
1150 UTF16 *ToPtr = &ToBuf[0];
1151
1152 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1153 &ToPtr, ToPtr + NumBytes,
1154 strictConversion);
1155 // Check for conversion failure.
1156 if (Result != conversionOK)
1157 Diag(Arg->getLocStart(),
1158 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1159 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001160 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001161}
1162
Chris Lattnerc27c6652007-12-20 00:05:45 +00001163/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1164/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001165bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1166 Expr *Fn = TheCall->getCallee();
1167 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001168 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001169 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001170 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1171 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001172 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001173 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001174 return true;
1175 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001176
1177 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001178 return Diag(TheCall->getLocEnd(),
1179 diag::err_typecheck_call_too_few_args_at_least)
1180 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001181 }
1182
John McCall5f8d6042011-08-27 01:09:30 +00001183 // Type-check the first argument normally.
1184 if (checkBuiltinArgument(*this, TheCall, 0))
1185 return true;
1186
Chris Lattnerc27c6652007-12-20 00:05:45 +00001187 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001188 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001189 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001190 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001191 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001192 else if (FunctionDecl *FD = getCurFunctionDecl())
1193 isVariadic = FD->isVariadic();
1194 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001195 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chris Lattnerc27c6652007-12-20 00:05:45 +00001197 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001198 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1199 return true;
1200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner30ce3442007-12-19 23:59:04 +00001202 // Verify that the second argument to the builtin is the last argument of the
1203 // current function or method.
1204 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001205 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Anders Carlsson88cf2262008-02-11 04:20:54 +00001207 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1208 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001209 // FIXME: This isn't correct for methods (results in bogus warning).
1210 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001211 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001212 if (CurBlock)
1213 LastArg = *(CurBlock->TheDecl->param_end()-1);
1214 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001215 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001216 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001217 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001218 SecondArgIsLastNamedArgument = PV == LastArg;
1219 }
1220 }
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner30ce3442007-12-19 23:59:04 +00001222 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001223 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001224 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1225 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001226}
Chris Lattner30ce3442007-12-19 23:59:04 +00001227
Chris Lattner1b9a0792007-12-20 00:26:33 +00001228/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1229/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001230bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1231 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001232 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001233 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001234 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001235 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001236 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001237 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001238 << SourceRange(TheCall->getArg(2)->getLocStart(),
1239 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001240
John Wiegley429bb272011-04-08 18:41:53 +00001241 ExprResult OrigArg0 = TheCall->getArg(0);
1242 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001243
Chris Lattner1b9a0792007-12-20 00:26:33 +00001244 // Do standard promotions between the two arguments, returning their common
1245 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001246 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001247 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1248 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001249
1250 // Make sure any conversions are pushed back into the call; this is
1251 // type safe since unordered compare builtins are declared as "_Bool
1252 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001253 TheCall->setArg(0, OrigArg0.get());
1254 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John Wiegley429bb272011-04-08 18:41:53 +00001256 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001257 return false;
1258
Chris Lattner1b9a0792007-12-20 00:26:33 +00001259 // If the common type isn't a real floating type, then the arguments were
1260 // invalid for this operation.
1261 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001262 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001263 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001264 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1265 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner1b9a0792007-12-20 00:26:33 +00001267 return false;
1268}
1269
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001270/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1271/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001272/// to check everything. We expect the last argument to be a floating point
1273/// value.
1274bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1275 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001276 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001277 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001278 if (TheCall->getNumArgs() > NumArgs)
1279 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001280 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001281 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001282 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001283 (*(TheCall->arg_end()-1))->getLocEnd());
1284
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001285 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Eli Friedman9ac6f622009-08-31 20:06:00 +00001287 if (OrigArg->isTypeDependent())
1288 return false;
1289
Chris Lattner81368fb2010-05-06 05:50:07 +00001290 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001291 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001292 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001293 diag::err_typecheck_call_invalid_unary_fp)
1294 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Chris Lattner81368fb2010-05-06 05:50:07 +00001296 // If this is an implicit conversion from float -> double, remove it.
1297 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1298 Expr *CastArg = Cast->getSubExpr();
1299 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1300 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1301 "promotion from float to double is the only expected cast here");
1302 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001303 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001304 }
1305 }
1306
Eli Friedman9ac6f622009-08-31 20:06:00 +00001307 return false;
1308}
1309
Eli Friedmand38617c2008-05-14 19:38:39 +00001310/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1311// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001312ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001313 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001314 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001315 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001316 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001317 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001318
Nate Begeman37b6a572010-06-08 00:16:34 +00001319 // Determine which of the following types of shufflevector we're checking:
1320 // 1) unary, vector mask: (lhs, mask)
1321 // 2) binary, vector mask: (lhs, rhs, mask)
1322 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1323 QualType resType = TheCall->getArg(0)->getType();
1324 unsigned numElements = 0;
1325
Douglas Gregorcde01732009-05-19 22:10:17 +00001326 if (!TheCall->getArg(0)->isTypeDependent() &&
1327 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001328 QualType LHSType = TheCall->getArg(0)->getType();
1329 QualType RHSType = TheCall->getArg(1)->getType();
1330
1331 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001332 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001333 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001334 TheCall->getArg(1)->getLocEnd());
1335 return ExprError();
1336 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001337
1338 numElements = LHSType->getAs<VectorType>()->getNumElements();
1339 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Nate Begeman37b6a572010-06-08 00:16:34 +00001341 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1342 // with mask. If so, verify that RHS is an integer vector type with the
1343 // same number of elts as lhs.
1344 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001345 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001346 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1347 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1348 << SourceRange(TheCall->getArg(1)->getLocStart(),
1349 TheCall->getArg(1)->getLocEnd());
1350 numResElements = numElements;
1351 }
1352 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001353 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001354 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001355 TheCall->getArg(1)->getLocEnd());
1356 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001357 } else if (numElements != numResElements) {
1358 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001359 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001360 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001361 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001362 }
1363
1364 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001365 if (TheCall->getArg(i)->isTypeDependent() ||
1366 TheCall->getArg(i)->isValueDependent())
1367 continue;
1368
Nate Begeman37b6a572010-06-08 00:16:34 +00001369 llvm::APSInt Result(32);
1370 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1371 return ExprError(Diag(TheCall->getLocStart(),
1372 diag::err_shufflevector_nonconstant_argument)
1373 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001374
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001375 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001376 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001377 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001378 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001379 }
1380
Chris Lattner5f9e2722011-07-23 10:55:15 +00001381 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001382
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001383 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001384 exprs.push_back(TheCall->getArg(i));
1385 TheCall->setArg(i, 0);
1386 }
1387
Nate Begemana88dc302009-08-12 02:10:25 +00001388 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001389 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001390 TheCall->getCallee()->getLocStart(),
1391 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001392}
Chris Lattner30ce3442007-12-19 23:59:04 +00001393
Daniel Dunbar4493f792008-07-21 22:59:13 +00001394/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1395// This is declared to take (const void*, ...) and can take two
1396// optional constant int args.
1397bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001398 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001399
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001400 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001401 return Diag(TheCall->getLocEnd(),
1402 diag::err_typecheck_call_too_many_args_at_most)
1403 << 0 /*function call*/ << 3 << NumArgs
1404 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001405
1406 // Argument 0 is checked for us and the remaining arguments must be
1407 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001408 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001409 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001410
Eli Friedman9aef7262009-12-04 00:30:06 +00001411 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001412 if (SemaBuiltinConstantArg(TheCall, i, Result))
1413 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Daniel Dunbar4493f792008-07-21 22:59:13 +00001415 // FIXME: gcc issues a warning and rewrites these to 0. These
1416 // seems especially odd for the third argument since the default
1417 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001418 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001419 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001420 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001421 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001422 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001423 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001424 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001425 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001426 }
1427 }
1428
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001429 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001430}
1431
Eric Christopher691ebc32010-04-17 02:26:23 +00001432/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1433/// TheCall is a constant expression.
1434bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1435 llvm::APSInt &Result) {
1436 Expr *Arg = TheCall->getArg(ArgNum);
1437 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1438 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1439
1440 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1441
1442 if (!Arg->isIntegerConstantExpr(Result, Context))
1443 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001444 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001445
Chris Lattner21fb98e2009-09-23 06:06:36 +00001446 return false;
1447}
1448
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001449/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1450/// int type). This simply type checks that type is one of the defined
1451/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001452// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001453bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001454 llvm::APSInt Result;
1455
1456 // Check constant-ness first.
1457 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1458 return true;
1459
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001460 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001461 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001462 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1463 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001464 }
1465
1466 return false;
1467}
1468
Eli Friedman586d6a82009-05-03 06:04:26 +00001469/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001470/// This checks that val is a constant 1.
1471bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1472 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001473 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001474
Eric Christopher691ebc32010-04-17 02:26:23 +00001475 // TODO: This is less than ideal. Overload this to take a value.
1476 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1477 return true;
1478
1479 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001480 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1481 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1482
1483 return false;
1484}
1485
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001486// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001487bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1488 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001489 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001490 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001491 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001492 if (E->isTypeDependent() || E->isValueDependent())
1493 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001494
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001495 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001496
David Blaikiea73cdcb2012-02-10 21:07:25 +00001497 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1498 // Technically -Wformat-nonliteral does not warn about this case.
1499 // The behavior of printf and friends in this case is implementation
1500 // dependent. Ideally if the format string cannot be null then
1501 // it should have a 'nonnull' attribute in the function prototype.
1502 return true;
1503
Ted Kremenekd30ef872009-01-12 23:09:09 +00001504 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001505 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001506 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001507 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001508 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001509 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001510 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001511 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1512 format_idx, firstDataArg, Type,
1513 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001514 }
1515
1516 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001517 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1518 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001519 }
1520
John McCall56ca35d2011-02-17 10:25:35 +00001521 case Stmt::OpaqueValueExprClass:
1522 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1523 E = src;
1524 goto tryAgain;
1525 }
1526 return false;
1527
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001528 case Stmt::PredefinedExprClass:
1529 // While __func__, etc., are technically not string literals, they
1530 // cannot contain format specifiers and thus are not a security
1531 // liability.
1532 return true;
1533
Ted Kremenek082d9362009-03-20 21:35:28 +00001534 case Stmt::DeclRefExprClass: {
1535 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenek082d9362009-03-20 21:35:28 +00001537 // As an exception, do not flag errors for variables binding to
1538 // const string literals.
1539 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1540 bool isConstant = false;
1541 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001542
Ted Kremenek082d9362009-03-20 21:35:28 +00001543 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1544 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001545 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001546 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001547 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001548 } else if (T->isObjCObjectPointerType()) {
1549 // In ObjC, there is usually no "const ObjectPointer" type,
1550 // so don't check if the pointee type is constant.
1551 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001552 }
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Ted Kremenek082d9362009-03-20 21:35:28 +00001554 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001555 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001556 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001557 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001558 Type, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Anders Carlssond966a552009-06-28 19:55:58 +00001561 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1562 // special check to see if the format string is a function parameter
1563 // of the function calling the printf function. If the function
1564 // has an attribute indicating it is a printf-like function, then we
1565 // should suppress warnings concerning non-literals being used in a call
1566 // to a vprintf function. For example:
1567 //
1568 // void
1569 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1570 // va_list ap;
1571 // va_start(ap, fmt);
1572 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1573 // ...
1574 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001575 if (HasVAListArg) {
1576 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1577 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1578 int PVIndex = PV->getFunctionScopeIndex() + 1;
1579 for (specific_attr_iterator<FormatAttr>
1580 i = ND->specific_attr_begin<FormatAttr>(),
1581 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1582 FormatAttr *PVFormat = *i;
1583 // adjust for implicit parameter
1584 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1585 if (MD->isInstance())
1586 ++PVIndex;
1587 // We also check if the formats are compatible.
1588 // We can't pass a 'scanf' string to a 'printf' function.
1589 if (PVIndex == PVFormat->getFormatIdx() &&
1590 Type == GetFormatStringType(PVFormat))
1591 return true;
1592 }
1593 }
1594 }
1595 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremenek082d9362009-03-20 21:35:28 +00001598 return false;
1599 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001600
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001601 case Stmt::CallExprClass:
1602 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001603 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001604 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1605 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1606 unsigned ArgIndex = FA->getFormatIdx();
1607 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1608 if (MD->isInstance())
1609 --ArgIndex;
1610 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001612 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1613 format_idx, firstDataArg, Type,
1614 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001615 }
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Anders Carlsson8f031b32009-06-27 04:05:33 +00001618 return false;
1619 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001620 case Stmt::ObjCStringLiteralClass:
1621 case Stmt::StringLiteralClass: {
1622 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Ted Kremenek082d9362009-03-20 21:35:28 +00001624 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001625 StrE = ObjCFExpr->getString();
1626 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001627 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Ted Kremenekd30ef872009-01-12 23:09:09 +00001629 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001630 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001631 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001632 return true;
1633 }
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Ted Kremenekd30ef872009-01-12 23:09:09 +00001635 return false;
1636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Ted Kremenek082d9362009-03-20 21:35:28 +00001638 default:
1639 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001640 }
1641}
1642
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001643void
Mike Stump1eb44332009-09-09 15:08:12 +00001644Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001645 const Expr * const *ExprArgs,
1646 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001647 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1648 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001649 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001650 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001651 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001652 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001653 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001654 }
1655}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001656
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001657Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1658 return llvm::StringSwitch<FormatStringType>(Format->getType())
1659 .Case("scanf", FST_Scanf)
1660 .Cases("printf", "printf0", FST_Printf)
1661 .Cases("NSString", "CFString", FST_NSString)
1662 .Case("strftime", FST_Strftime)
1663 .Case("strfmon", FST_Strfmon)
1664 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1665 .Default(FST_Unknown);
1666}
1667
Ted Kremenek826a3452010-07-16 02:11:22 +00001668/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1669/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001670void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1671 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001672 // The way the format attribute works in GCC, the implicit this argument
1673 // of member functions is counted. However, it doesn't appear in our own
1674 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001675 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001676 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1677 IsCXXMember, TheCall->getRParenLoc(),
1678 TheCall->getCallee()->getSourceRange());
1679}
1680
1681void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1682 unsigned NumArgs, bool IsCXXMember,
1683 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001684 bool HasVAListArg = Format->getFirstArg() == 0;
1685 unsigned format_idx = Format->getFormatIdx() - 1;
1686 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1687 if (IsCXXMember) {
1688 if (format_idx == 0)
1689 return;
1690 --format_idx;
1691 if(firstDataArg != 0)
1692 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001693 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001694 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1695 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001696}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001697
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001698void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1699 bool HasVAListArg, unsigned format_idx,
1700 unsigned firstDataArg, FormatStringType Type,
1701 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001702 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001703 if (format_idx >= NumArgs) {
1704 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001705 return;
1706 }
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001708 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Chris Lattner59907c42007-08-10 20:18:51 +00001710 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001711 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001712 // Dynamically generated format strings are difficult to
1713 // automatically vet at compile time. Requiring that format strings
1714 // are string literals: (1) permits the checking of format strings by
1715 // the compiler and thereby (2) can practically remove the source of
1716 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001717
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001719 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001721 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001722 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001723 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001724 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001725
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001726 // Strftime is particular as it always uses a single 'time' argument,
1727 // so it is safe to pass a non-literal string.
1728 if (Type == FST_Strftime)
1729 return;
1730
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001731 // Do not emit diag when the string param is a macro expansion and the
1732 // format is either NSString or CFString. This is a hack to prevent
1733 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1734 // which are usually used in place of NS and CF string literals.
1735 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1736 return;
1737
Chris Lattner655f1412009-04-29 04:59:47 +00001738 // If there are no arguments specified, warn with -Wformat-security, otherwise
1739 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001740 if (NumArgs == format_idx+1)
1741 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001742 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001743 << OrigFormatExpr->getSourceRange();
1744 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001745 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001746 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001747 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001748}
Ted Kremenek71895b92007-08-14 17:39:48 +00001749
Ted Kremeneke0e53132010-01-28 23:39:18 +00001750namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001751class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1752protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001753 Sema &S;
1754 const StringLiteral *FExpr;
1755 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001756 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001757 const unsigned NumDataArgs;
1758 const bool IsObjCLiteral;
1759 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001760 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001761 const Expr * const *Args;
1762 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001763 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001764 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001765 bool usesPositionalArgs;
1766 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001767 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001768public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001769 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001770 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001772 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001773 Expr **args, unsigned numArgs,
1774 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001775 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001776 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001777 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001778 IsObjCLiteral(isObjCLiteral), Beg(beg),
1779 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001780 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001781 usesPositionalArgs(false), atFirstArg(true),
1782 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001783 CoveredArgs.resize(numDataArgs);
1784 CoveredArgs.reset();
1785 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001786
Ted Kremenek07d161f2010-01-29 01:50:07 +00001787 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001788
Ted Kremenek826a3452010-07-16 02:11:22 +00001789 void HandleIncompleteSpecifier(const char *startSpecifier,
1790 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001791
1792 void HandleNonStandardLengthModifier(
1793 const analyze_format_string::LengthModifier &LM,
1794 const char *startSpecifier, unsigned specifierLen);
1795
1796 void HandleNonStandardConversionSpecifier(
1797 const analyze_format_string::ConversionSpecifier &CS,
1798 const char *startSpecifier, unsigned specifierLen);
1799
1800 void HandleNonStandardConversionSpecification(
1801 const analyze_format_string::LengthModifier &LM,
1802 const analyze_format_string::ConversionSpecifier &CS,
1803 const char *startSpecifier, unsigned specifierLen);
1804
Hans Wennborgf8562642012-03-09 10:10:54 +00001805 virtual void HandlePosition(const char *startPos, unsigned posLen);
1806
Ted Kremenekefaff192010-02-27 01:41:03 +00001807 virtual void HandleInvalidPosition(const char *startSpecifier,
1808 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001809 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001810
1811 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1812
Ted Kremeneke0e53132010-01-28 23:39:18 +00001813 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001814
Richard Trieu55733de2011-10-28 00:41:25 +00001815 template <typename Range>
1816 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1817 const Expr *ArgumentExpr,
1818 PartialDiagnostic PDiag,
1819 SourceLocation StringLoc,
1820 bool IsStringLocation, Range StringRange,
1821 FixItHint Fixit = FixItHint());
1822
Ted Kremenek826a3452010-07-16 02:11:22 +00001823protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001824 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1825 const char *startSpec,
1826 unsigned specifierLen,
1827 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001828
1829 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1830 const char *startSpec,
1831 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001832
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001833 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001834 CharSourceRange getSpecifierRange(const char *startSpecifier,
1835 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001836 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001837
Ted Kremenek0d277352010-01-29 01:06:55 +00001838 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001839
1840 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1841 const analyze_format_string::ConversionSpecifier &CS,
1842 const char *startSpecifier, unsigned specifierLen,
1843 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001844
1845 template <typename Range>
1846 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1847 bool IsStringLocation, Range StringRange,
1848 FixItHint Fixit = FixItHint());
1849
1850 void CheckPositionalAndNonpositionalArgs(
1851 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001852};
1853}
1854
Ted Kremenek826a3452010-07-16 02:11:22 +00001855SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001856 return OrigFormatExpr->getSourceRange();
1857}
1858
Ted Kremenek826a3452010-07-16 02:11:22 +00001859CharSourceRange CheckFormatHandler::
1860getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001861 SourceLocation Start = getLocationOfByte(startSpecifier);
1862 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1863
1864 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001865 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001866
1867 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001868}
1869
Ted Kremenek826a3452010-07-16 02:11:22 +00001870SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001871 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001872}
1873
Ted Kremenek826a3452010-07-16 02:11:22 +00001874void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1875 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001876 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1877 getLocationOfByte(startSpecifier),
1878 /*IsStringLocation*/true,
1879 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001880}
1881
Hans Wennborg76517422012-02-22 10:17:01 +00001882void CheckFormatHandler::HandleNonStandardLengthModifier(
1883 const analyze_format_string::LengthModifier &LM,
1884 const char *startSpecifier, unsigned specifierLen) {
1885 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001886 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001887 getLocationOfByte(LM.getStart()),
1888 /*IsStringLocation*/true,
1889 getSpecifierRange(startSpecifier, specifierLen));
1890}
1891
1892void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1893 const analyze_format_string::ConversionSpecifier &CS,
1894 const char *startSpecifier, unsigned specifierLen) {
1895 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001896 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001897 getLocationOfByte(CS.getStart()),
1898 /*IsStringLocation*/true,
1899 getSpecifierRange(startSpecifier, specifierLen));
1900}
1901
1902void CheckFormatHandler::HandleNonStandardConversionSpecification(
1903 const analyze_format_string::LengthModifier &LM,
1904 const analyze_format_string::ConversionSpecifier &CS,
1905 const char *startSpecifier, unsigned specifierLen) {
1906 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1907 << LM.toString() << CS.toString(),
1908 getLocationOfByte(LM.getStart()),
1909 /*IsStringLocation*/true,
1910 getSpecifierRange(startSpecifier, specifierLen));
1911}
1912
Hans Wennborgf8562642012-03-09 10:10:54 +00001913void CheckFormatHandler::HandlePosition(const char *startPos,
1914 unsigned posLen) {
1915 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1916 getLocationOfByte(startPos),
1917 /*IsStringLocation*/true,
1918 getSpecifierRange(startPos, posLen));
1919}
1920
Ted Kremenekefaff192010-02-27 01:41:03 +00001921void
Ted Kremenek826a3452010-07-16 02:11:22 +00001922CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1923 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001924 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1925 << (unsigned) p,
1926 getLocationOfByte(startPos), /*IsStringLocation*/true,
1927 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001928}
1929
Ted Kremenek826a3452010-07-16 02:11:22 +00001930void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001931 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001932 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1933 getLocationOfByte(startPos),
1934 /*IsStringLocation*/true,
1935 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001936}
1937
Ted Kremenek826a3452010-07-16 02:11:22 +00001938void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001939 if (!IsObjCLiteral) {
1940 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001941 EmitFormatDiagnostic(
1942 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1943 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1944 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001945 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001946}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001947
Ted Kremenek826a3452010-07-16 02:11:22 +00001948const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001949 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001950}
1951
1952void CheckFormatHandler::DoneProcessing() {
1953 // Does the number of data arguments exceed the number of
1954 // format conversions in the format string?
1955 if (!HasVAListArg) {
1956 // Find any arguments that weren't covered.
1957 CoveredArgs.flip();
1958 signed notCoveredArg = CoveredArgs.find_first();
1959 if (notCoveredArg >= 0) {
1960 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001961 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1962 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1963 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001964 }
1965 }
1966}
1967
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001968bool
1969CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1970 SourceLocation Loc,
1971 const char *startSpec,
1972 unsigned specifierLen,
1973 const char *csStart,
1974 unsigned csLen) {
1975
1976 bool keepGoing = true;
1977 if (argIndex < NumDataArgs) {
1978 // Consider the argument coverered, even though the specifier doesn't
1979 // make sense.
1980 CoveredArgs.set(argIndex);
1981 }
1982 else {
1983 // If argIndex exceeds the number of data arguments we
1984 // don't issue a warning because that is just a cascade of warnings (and
1985 // they may have intended '%%' anyway). We don't want to continue processing
1986 // the format string after this point, however, as we will like just get
1987 // gibberish when trying to match arguments.
1988 keepGoing = false;
1989 }
1990
Richard Trieu55733de2011-10-28 00:41:25 +00001991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1992 << StringRef(csStart, csLen),
1993 Loc, /*IsStringLocation*/true,
1994 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001995
1996 return keepGoing;
1997}
1998
Richard Trieu55733de2011-10-28 00:41:25 +00001999void
2000CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2001 const char *startSpec,
2002 unsigned specifierLen) {
2003 EmitFormatDiagnostic(
2004 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2005 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2006}
2007
Ted Kremenek666a1972010-07-26 19:45:42 +00002008bool
2009CheckFormatHandler::CheckNumArgs(
2010 const analyze_format_string::FormatSpecifier &FS,
2011 const analyze_format_string::ConversionSpecifier &CS,
2012 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2013
2014 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002015 PartialDiagnostic PDiag = FS.usesPositionalArg()
2016 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2017 << (argIndex+1) << NumDataArgs)
2018 : S.PDiag(diag::warn_printf_insufficient_data_args);
2019 EmitFormatDiagnostic(
2020 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2021 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002022 return false;
2023 }
2024 return true;
2025}
2026
Richard Trieu55733de2011-10-28 00:41:25 +00002027template<typename Range>
2028void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2029 SourceLocation Loc,
2030 bool IsStringLocation,
2031 Range StringRange,
2032 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002033 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002034 Loc, IsStringLocation, StringRange, FixIt);
2035}
2036
2037/// \brief If the format string is not within the funcion call, emit a note
2038/// so that the function call and string are in diagnostic messages.
2039///
2040/// \param inFunctionCall if true, the format string is within the function
2041/// call and only one diagnostic message will be produced. Otherwise, an
2042/// extra note will be emitted pointing to location of the format string.
2043///
2044/// \param ArgumentExpr the expression that is passed as the format string
2045/// argument in the function call. Used for getting locations when two
2046/// diagnostics are emitted.
2047///
2048/// \param PDiag the callee should already have provided any strings for the
2049/// diagnostic message. This function only adds locations and fixits
2050/// to diagnostics.
2051///
2052/// \param Loc primary location for diagnostic. If two diagnostics are
2053/// required, one will be at Loc and a new SourceLocation will be created for
2054/// the other one.
2055///
2056/// \param IsStringLocation if true, Loc points to the format string should be
2057/// used for the note. Otherwise, Loc points to the argument list and will
2058/// be used with PDiag.
2059///
2060/// \param StringRange some or all of the string to highlight. This is
2061/// templated so it can accept either a CharSourceRange or a SourceRange.
2062///
2063/// \param Fixit optional fix it hint for the format string.
2064template<typename Range>
2065void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2066 const Expr *ArgumentExpr,
2067 PartialDiagnostic PDiag,
2068 SourceLocation Loc,
2069 bool IsStringLocation,
2070 Range StringRange,
2071 FixItHint FixIt) {
2072 if (InFunctionCall)
2073 S.Diag(Loc, PDiag) << StringRange << FixIt;
2074 else {
2075 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2076 << ArgumentExpr->getSourceRange();
2077 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2078 diag::note_format_string_defined)
2079 << StringRange << FixIt;
2080 }
2081}
2082
Ted Kremenek826a3452010-07-16 02:11:22 +00002083//===--- CHECK: Printf format string checking ------------------------------===//
2084
2085namespace {
2086class CheckPrintfHandler : public CheckFormatHandler {
2087public:
2088 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2089 const Expr *origFormatExpr, unsigned firstDataArg,
2090 unsigned numDataArgs, bool isObjCLiteral,
2091 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002092 Expr **Args, unsigned NumArgs,
2093 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002094 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2095 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002096 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002097
2098
2099 bool HandleInvalidPrintfConversionSpecifier(
2100 const analyze_printf::PrintfSpecifier &FS,
2101 const char *startSpecifier,
2102 unsigned specifierLen);
2103
2104 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2105 const char *startSpecifier,
2106 unsigned specifierLen);
2107
2108 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2109 const char *startSpecifier, unsigned specifierLen);
2110 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2111 const analyze_printf::OptionalAmount &Amt,
2112 unsigned type,
2113 const char *startSpecifier, unsigned specifierLen);
2114 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2115 const analyze_printf::OptionalFlag &flag,
2116 const char *startSpecifier, unsigned specifierLen);
2117 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2118 const analyze_printf::OptionalFlag &ignoredFlag,
2119 const analyze_printf::OptionalFlag &flag,
2120 const char *startSpecifier, unsigned specifierLen);
2121};
2122}
2123
2124bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2125 const analyze_printf::PrintfSpecifier &FS,
2126 const char *startSpecifier,
2127 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002128 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002129 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002130
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002131 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2132 getLocationOfByte(CS.getStart()),
2133 startSpecifier, specifierLen,
2134 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002135}
2136
Ted Kremenek826a3452010-07-16 02:11:22 +00002137bool CheckPrintfHandler::HandleAmount(
2138 const analyze_format_string::OptionalAmount &Amt,
2139 unsigned k, const char *startSpecifier,
2140 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002141
2142 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002143 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002144 unsigned argIndex = Amt.getArgIndex();
2145 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002146 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2147 << k,
2148 getLocationOfByte(Amt.getStart()),
2149 /*IsStringLocation*/true,
2150 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002151 // Don't do any more checking. We will just emit
2152 // spurious errors.
2153 return false;
2154 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002155
Ted Kremenek0d277352010-01-29 01:06:55 +00002156 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002157 // Although not in conformance with C99, we also allow the argument to be
2158 // an 'unsigned int' as that is a reasonably safe case. GCC also
2159 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002160 CoveredArgs.set(argIndex);
2161 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002162 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002163
2164 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2165 assert(ATR.isValid());
2166
2167 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002168 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002169 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002170 << T << Arg->getSourceRange(),
2171 getLocationOfByte(Amt.getStart()),
2172 /*IsStringLocation*/true,
2173 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002174 // Don't do any more checking. We will just emit
2175 // spurious errors.
2176 return false;
2177 }
2178 }
2179 }
2180 return true;
2181}
Ted Kremenek0d277352010-01-29 01:06:55 +00002182
Tom Caree4ee9662010-06-17 19:00:27 +00002183void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002184 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002185 const analyze_printf::OptionalAmount &Amt,
2186 unsigned type,
2187 const char *startSpecifier,
2188 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002189 const analyze_printf::PrintfConversionSpecifier &CS =
2190 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002191
Richard Trieu55733de2011-10-28 00:41:25 +00002192 FixItHint fixit =
2193 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2194 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2195 Amt.getConstantLength()))
2196 : FixItHint();
2197
2198 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2199 << type << CS.toString(),
2200 getLocationOfByte(Amt.getStart()),
2201 /*IsStringLocation*/true,
2202 getSpecifierRange(startSpecifier, specifierLen),
2203 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002204}
2205
Ted Kremenek826a3452010-07-16 02:11:22 +00002206void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002207 const analyze_printf::OptionalFlag &flag,
2208 const char *startSpecifier,
2209 unsigned specifierLen) {
2210 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002211 const analyze_printf::PrintfConversionSpecifier &CS =
2212 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002213 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2214 << flag.toString() << CS.toString(),
2215 getLocationOfByte(flag.getPosition()),
2216 /*IsStringLocation*/true,
2217 getSpecifierRange(startSpecifier, specifierLen),
2218 FixItHint::CreateRemoval(
2219 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002220}
2221
2222void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002223 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002224 const analyze_printf::OptionalFlag &ignoredFlag,
2225 const analyze_printf::OptionalFlag &flag,
2226 const char *startSpecifier,
2227 unsigned specifierLen) {
2228 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002229 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2230 << ignoredFlag.toString() << flag.toString(),
2231 getLocationOfByte(ignoredFlag.getPosition()),
2232 /*IsStringLocation*/true,
2233 getSpecifierRange(startSpecifier, specifierLen),
2234 FixItHint::CreateRemoval(
2235 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002236}
2237
Ted Kremeneke0e53132010-01-28 23:39:18 +00002238bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002239CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002240 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002241 const char *startSpecifier,
2242 unsigned specifierLen) {
2243
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002244 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002245 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002246 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002247
Ted Kremenekbaa40062010-07-19 22:01:06 +00002248 if (FS.consumesDataArgument()) {
2249 if (atFirstArg) {
2250 atFirstArg = false;
2251 usesPositionalArgs = FS.usesPositionalArg();
2252 }
2253 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002254 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2255 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002256 return false;
2257 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002258 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002259
Ted Kremenekefaff192010-02-27 01:41:03 +00002260 // First check if the field width, precision, and conversion specifier
2261 // have matching data arguments.
2262 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2263 startSpecifier, specifierLen)) {
2264 return false;
2265 }
2266
2267 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2268 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002269 return false;
2270 }
2271
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002272 if (!CS.consumesDataArgument()) {
2273 // FIXME: Technically specifying a precision or field width here
2274 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002275 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002276 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002277
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002278 // Consume the argument.
2279 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002280 if (argIndex < NumDataArgs) {
2281 // The check to see if the argIndex is valid will come later.
2282 // We set the bit here because we may exit early from this
2283 // function if we encounter some other error.
2284 CoveredArgs.set(argIndex);
2285 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002286
2287 // Check for using an Objective-C specific conversion specifier
2288 // in a non-ObjC literal.
2289 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002290 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2291 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002292 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002293
Tom Caree4ee9662010-06-17 19:00:27 +00002294 // Check for invalid use of field width
2295 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002296 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002297 startSpecifier, specifierLen);
2298 }
2299
2300 // Check for invalid use of precision
2301 if (!FS.hasValidPrecision()) {
2302 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2303 startSpecifier, specifierLen);
2304 }
2305
2306 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002307 if (!FS.hasValidThousandsGroupingPrefix())
2308 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002309 if (!FS.hasValidLeadingZeros())
2310 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2311 if (!FS.hasValidPlusPrefix())
2312 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002313 if (!FS.hasValidSpacePrefix())
2314 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002315 if (!FS.hasValidAlternativeForm())
2316 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2317 if (!FS.hasValidLeftJustified())
2318 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2319
2320 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002321 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2322 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2323 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002324 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2325 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2326 startSpecifier, specifierLen);
2327
2328 // Check the length modifier is valid with the given conversion specifier.
2329 const LengthModifier &LM = FS.getLengthModifier();
2330 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002331 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2332 << LM.toString() << CS.toString(),
2333 getLocationOfByte(LM.getStart()),
2334 /*IsStringLocation*/true,
2335 getSpecifierRange(startSpecifier, specifierLen),
2336 FixItHint::CreateRemoval(
2337 getSpecifierRange(LM.getStart(),
2338 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002339 if (!FS.hasStandardLengthModifier())
2340 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002341 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002342 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2343 if (!FS.hasStandardLengthConversionCombination())
2344 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2345 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002346
2347 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002348 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002349 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002350 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2351 getLocationOfByte(CS.getStart()),
2352 /*IsStringLocation*/true,
2353 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002354 // Continue checking the other format specifiers.
2355 return true;
2356 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002357
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002358 // The remaining checks depend on the data arguments.
2359 if (HasVAListArg)
2360 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002361
Ted Kremenek666a1972010-07-26 19:45:42 +00002362 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002363 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002364
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002365 // Now type check the data expression that matches the
2366 // format specifier.
2367 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002368 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2369 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002370 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2371 // Check if we didn't match because of an implicit cast from a 'char'
2372 // or 'short' to an 'int'. This is done because printf is a varargs
2373 // function.
2374 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002375 if (ICE->getType() == S.Context.IntTy) {
2376 // All further checking is done on the subexpression.
2377 Ex = ICE->getSubExpr();
2378 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002379 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002380 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002381
2382 // We may be able to offer a FixItHint if it is a supported type.
2383 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002384 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002385 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002386
2387 if (success) {
2388 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002389 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002390 llvm::raw_svector_ostream os(buf);
2391 fixedFS.toString(os);
2392
Richard Trieu55733de2011-10-28 00:41:25 +00002393 EmitFormatDiagnostic(
2394 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002395 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002396 << Ex->getSourceRange(),
2397 getLocationOfByte(CS.getStart()),
2398 /*IsStringLocation*/true,
2399 getSpecifierRange(startSpecifier, specifierLen),
2400 FixItHint::CreateReplacement(
2401 getSpecifierRange(startSpecifier, specifierLen),
2402 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002403 }
2404 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002405 EmitFormatDiagnostic(
2406 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2407 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2408 << getSpecifierRange(startSpecifier, specifierLen)
2409 << Ex->getSourceRange(),
2410 getLocationOfByte(CS.getStart()),
2411 true,
2412 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002413 }
2414 }
2415
Ted Kremeneke0e53132010-01-28 23:39:18 +00002416 return true;
2417}
2418
Ted Kremenek826a3452010-07-16 02:11:22 +00002419//===--- CHECK: Scanf format string checking ------------------------------===//
2420
2421namespace {
2422class CheckScanfHandler : public CheckFormatHandler {
2423public:
2424 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2425 const Expr *origFormatExpr, unsigned firstDataArg,
2426 unsigned numDataArgs, bool isObjCLiteral,
2427 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002428 Expr **Args, unsigned NumArgs,
2429 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002430 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2431 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002432 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002433
2434 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2435 const char *startSpecifier,
2436 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002437
2438 bool HandleInvalidScanfConversionSpecifier(
2439 const analyze_scanf::ScanfSpecifier &FS,
2440 const char *startSpecifier,
2441 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002442
2443 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002444};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002445}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002446
Ted Kremenekb7c21012010-07-16 18:28:03 +00002447void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2448 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002449 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2450 getLocationOfByte(end), /*IsStringLocation*/true,
2451 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002452}
2453
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002454bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2455 const analyze_scanf::ScanfSpecifier &FS,
2456 const char *startSpecifier,
2457 unsigned specifierLen) {
2458
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002459 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002460 FS.getConversionSpecifier();
2461
2462 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2463 getLocationOfByte(CS.getStart()),
2464 startSpecifier, specifierLen,
2465 CS.getStart(), CS.getLength());
2466}
2467
Ted Kremenek826a3452010-07-16 02:11:22 +00002468bool CheckScanfHandler::HandleScanfSpecifier(
2469 const analyze_scanf::ScanfSpecifier &FS,
2470 const char *startSpecifier,
2471 unsigned specifierLen) {
2472
2473 using namespace analyze_scanf;
2474 using namespace analyze_format_string;
2475
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002476 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002477
Ted Kremenekbaa40062010-07-19 22:01:06 +00002478 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2479 // be used to decide if we are using positional arguments consistently.
2480 if (FS.consumesDataArgument()) {
2481 if (atFirstArg) {
2482 atFirstArg = false;
2483 usesPositionalArgs = FS.usesPositionalArg();
2484 }
2485 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002486 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2487 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002488 return false;
2489 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002490 }
2491
2492 // Check if the field with is non-zero.
2493 const OptionalAmount &Amt = FS.getFieldWidth();
2494 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2495 if (Amt.getConstantAmount() == 0) {
2496 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2497 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002498 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2499 getLocationOfByte(Amt.getStart()),
2500 /*IsStringLocation*/true, R,
2501 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002502 }
2503 }
2504
2505 if (!FS.consumesDataArgument()) {
2506 // FIXME: Technically specifying a precision or field width here
2507 // makes no sense. Worth issuing a warning at some point.
2508 return true;
2509 }
2510
2511 // Consume the argument.
2512 unsigned argIndex = FS.getArgIndex();
2513 if (argIndex < NumDataArgs) {
2514 // The check to see if the argIndex is valid will come later.
2515 // We set the bit here because we may exit early from this
2516 // function if we encounter some other error.
2517 CoveredArgs.set(argIndex);
2518 }
2519
Ted Kremenek1e51c202010-07-20 20:04:47 +00002520 // Check the length modifier is valid with the given conversion specifier.
2521 const LengthModifier &LM = FS.getLengthModifier();
2522 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002523 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2525 << LM.toString() << CS.toString()
2526 << getSpecifierRange(startSpecifier, specifierLen),
2527 getLocationOfByte(LM.getStart()),
2528 /*IsStringLocation*/true, R,
2529 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002530 }
2531
Hans Wennborg76517422012-02-22 10:17:01 +00002532 if (!FS.hasStandardLengthModifier())
2533 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002534 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002535 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2536 if (!FS.hasStandardLengthConversionCombination())
2537 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2538 specifierLen);
2539
Ted Kremenek826a3452010-07-16 02:11:22 +00002540 // The remaining checks depend on the data arguments.
2541 if (HasVAListArg)
2542 return true;
2543
Ted Kremenek666a1972010-07-26 19:45:42 +00002544 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002545 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002546
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002547 // Check that the argument type matches the format specifier.
2548 const Expr *Ex = getDataArg(argIndex);
2549 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2550 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2551 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002552 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002553 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002554
2555 if (success) {
2556 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002557 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002558 llvm::raw_svector_ostream os(buf);
2559 fixedFS.toString(os);
2560
2561 EmitFormatDiagnostic(
2562 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2563 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2564 << Ex->getSourceRange(),
2565 getLocationOfByte(CS.getStart()),
2566 /*IsStringLocation*/true,
2567 getSpecifierRange(startSpecifier, specifierLen),
2568 FixItHint::CreateReplacement(
2569 getSpecifierRange(startSpecifier, specifierLen),
2570 os.str()));
2571 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002572 EmitFormatDiagnostic(
2573 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002574 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002575 << Ex->getSourceRange(),
2576 getLocationOfByte(CS.getStart()),
2577 /*IsStringLocation*/true,
2578 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002579 }
2580 }
2581
Ted Kremenek826a3452010-07-16 02:11:22 +00002582 return true;
2583}
2584
2585void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002586 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002587 Expr **Args, unsigned NumArgs,
2588 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002589 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002590 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002591
Ted Kremeneke0e53132010-01-28 23:39:18 +00002592 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002593 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002594 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002595 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002596 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2597 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002598 return;
2599 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002600
Ted Kremeneke0e53132010-01-28 23:39:18 +00002601 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002602 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002603 const char *Str = StrRef.data();
2604 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002605 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002606
Ted Kremeneke0e53132010-01-28 23:39:18 +00002607 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002608 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002609 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002610 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002611 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2612 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002613 return;
2614 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002615
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002616 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002617 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002618 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002619 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002620 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002621
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002622 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002623 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002624 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002625 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002626 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002627 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002628 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002629 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002630
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002631 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002632 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002633 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002634 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002635}
2636
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002637//===--- CHECK: Standard memory functions ---------------------------------===//
2638
Douglas Gregor2a053a32011-05-03 20:05:22 +00002639/// \brief Determine whether the given type is a dynamic class type (e.g.,
2640/// whether it has a vtable).
2641static bool isDynamicClassType(QualType T) {
2642 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2643 if (CXXRecordDecl *Definition = Record->getDefinition())
2644 if (Definition->isDynamicClass())
2645 return true;
2646
2647 return false;
2648}
2649
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002650/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002651/// otherwise returns NULL.
2652static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002653 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002654 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2655 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2656 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002657
Chandler Carruth000d4282011-06-16 09:09:40 +00002658 return 0;
2659}
2660
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002661/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002662static QualType getSizeOfArgType(const Expr* E) {
2663 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2664 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2665 if (SizeOf->getKind() == clang::UETT_SizeOf)
2666 return SizeOf->getTypeOfArgument();
2667
2668 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002669}
2670
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002671/// \brief Check for dangerous or invalid arguments to memset().
2672///
Chandler Carruth929f0132011-06-03 06:23:57 +00002673/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002674/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2675/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002676///
2677/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002678void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002679 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002680 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002681 assert(BId != 0);
2682
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002683 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002684 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002685 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002686 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002687 return;
2688
Anna Zaks0a151a12012-01-17 00:37:07 +00002689 unsigned LastArg = (BId == Builtin::BImemset ||
2690 BId == Builtin::BIstrndup ? 1 : 2);
2691 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002692 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002693
2694 // We have special checking when the length is a sizeof expression.
2695 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2696 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2697 llvm::FoldingSetNodeID SizeOfArgID;
2698
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002699 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2700 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002701 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002702
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002703 QualType DestTy = Dest->getType();
2704 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2705 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002706
Chandler Carruth000d4282011-06-16 09:09:40 +00002707 // Never warn about void type pointers. This can be used to suppress
2708 // false positives.
2709 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002710 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002711
Chandler Carruth000d4282011-06-16 09:09:40 +00002712 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2713 // actually comparing the expressions for equality. Because computing the
2714 // expression IDs can be expensive, we only do this if the diagnostic is
2715 // enabled.
2716 if (SizeOfArg &&
2717 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2718 SizeOfArg->getExprLoc())) {
2719 // We only compute IDs for expressions if the warning is enabled, and
2720 // cache the sizeof arg's ID.
2721 if (SizeOfArgID == llvm::FoldingSetNodeID())
2722 SizeOfArg->Profile(SizeOfArgID, Context, true);
2723 llvm::FoldingSetNodeID DestID;
2724 Dest->Profile(DestID, Context, true);
2725 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002726 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2727 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002728 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2729 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2730 if (UnaryOp->getOpcode() == UO_AddrOf)
2731 ActionIdx = 1; // If its an address-of operator, just remove it.
2732 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2733 ActionIdx = 2; // If the pointee's size is sizeof(char),
2734 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002735 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002736 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002737 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2738 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002739 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002740 << Dest->getSourceRange()
2741 << SizeOfArg->getSourceRange());
2742 break;
2743 }
2744 }
2745
2746 // Also check for cases where the sizeof argument is the exact same
2747 // type as the memory argument, and where it points to a user-defined
2748 // record type.
2749 if (SizeOfArgTy != QualType()) {
2750 if (PointeeTy->isRecordType() &&
2751 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2752 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2753 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2754 << FnName << SizeOfArgTy << ArgIdx
2755 << PointeeTy << Dest->getSourceRange()
2756 << LenExpr->getSourceRange());
2757 break;
2758 }
Nico Webere4a1c642011-06-14 16:14:58 +00002759 }
2760
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002761 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002762 if (isDynamicClassType(PointeeTy)) {
2763
2764 unsigned OperationType = 0;
2765 // "overwritten" if we're warning about the destination for any call
2766 // but memcmp; otherwise a verb appropriate to the call.
2767 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2768 if (BId == Builtin::BImemcpy)
2769 OperationType = 1;
2770 else if(BId == Builtin::BImemmove)
2771 OperationType = 2;
2772 else if (BId == Builtin::BImemcmp)
2773 OperationType = 3;
2774 }
2775
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002776 DiagRuntimeBehavior(
2777 Dest->getExprLoc(), Dest,
2778 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002779 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002780 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002781 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002782 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002783 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2784 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002785 DiagRuntimeBehavior(
2786 Dest->getExprLoc(), Dest,
2787 PDiag(diag::warn_arc_object_memaccess)
2788 << ArgIdx << FnName << PointeeTy
2789 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002790 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002791 continue;
John McCallf85e1932011-06-15 23:02:42 +00002792
2793 DiagRuntimeBehavior(
2794 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002795 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002796 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2797 break;
2798 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002799 }
2800}
2801
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002802// A little helper routine: ignore addition and subtraction of integer literals.
2803// This intentionally does not ignore all integer constant expressions because
2804// we don't want to remove sizeof().
2805static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2806 Ex = Ex->IgnoreParenCasts();
2807
2808 for (;;) {
2809 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2810 if (!BO || !BO->isAdditiveOp())
2811 break;
2812
2813 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2814 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2815
2816 if (isa<IntegerLiteral>(RHS))
2817 Ex = LHS;
2818 else if (isa<IntegerLiteral>(LHS))
2819 Ex = RHS;
2820 else
2821 break;
2822 }
2823
2824 return Ex;
2825}
2826
2827// Warn if the user has made the 'size' argument to strlcpy or strlcat
2828// be the size of the source, instead of the destination.
2829void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2830 IdentifierInfo *FnName) {
2831
2832 // Don't crash if the user has the wrong number of arguments
2833 if (Call->getNumArgs() != 3)
2834 return;
2835
2836 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2837 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2838 const Expr *CompareWithSrc = NULL;
2839
2840 // Look for 'strlcpy(dst, x, sizeof(x))'
2841 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2842 CompareWithSrc = Ex;
2843 else {
2844 // Look for 'strlcpy(dst, x, strlen(x))'
2845 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002846 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002847 && SizeCall->getNumArgs() == 1)
2848 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2849 }
2850 }
2851
2852 if (!CompareWithSrc)
2853 return;
2854
2855 // Determine if the argument to sizeof/strlen is equal to the source
2856 // argument. In principle there's all kinds of things you could do
2857 // here, for instance creating an == expression and evaluating it with
2858 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2859 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2860 if (!SrcArgDRE)
2861 return;
2862
2863 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2864 if (!CompareWithSrcDRE ||
2865 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2866 return;
2867
2868 const Expr *OriginalSizeArg = Call->getArg(2);
2869 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2870 << OriginalSizeArg->getSourceRange() << FnName;
2871
2872 // Output a FIXIT hint if the destination is an array (rather than a
2873 // pointer to an array). This could be enhanced to handle some
2874 // pointers if we know the actual size, like if DstArg is 'array+2'
2875 // we could say 'sizeof(array)-2'.
2876 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002877 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002878
Ted Kremenek8f746222011-08-18 22:48:41 +00002879 // Only handle constant-sized or VLAs, but not flexible members.
2880 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2881 // Only issue the FIXIT for arrays of size > 1.
2882 if (CAT->getSize().getSExtValue() <= 1)
2883 return;
2884 } else if (!DstArgTy->isVariableArrayType()) {
2885 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002886 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002887
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002888 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002889 llvm::raw_svector_ostream OS(sizeString);
2890 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002891 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002892 OS << ")";
2893
2894 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2895 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2896 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002897}
2898
Anna Zaksc36bedc2012-02-01 19:08:57 +00002899/// Check if two expressions refer to the same declaration.
2900static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2901 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2902 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2903 return D1->getDecl() == D2->getDecl();
2904 return false;
2905}
2906
2907static const Expr *getStrlenExprArg(const Expr *E) {
2908 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2909 const FunctionDecl *FD = CE->getDirectCallee();
2910 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2911 return 0;
2912 return CE->getArg(0)->IgnoreParenCasts();
2913 }
2914 return 0;
2915}
2916
2917// Warn on anti-patterns as the 'size' argument to strncat.
2918// The correct size argument should look like following:
2919// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2920void Sema::CheckStrncatArguments(const CallExpr *CE,
2921 IdentifierInfo *FnName) {
2922 // Don't crash if the user has the wrong number of arguments.
2923 if (CE->getNumArgs() < 3)
2924 return;
2925 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2926 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2927 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2928
2929 // Identify common expressions, which are wrongly used as the size argument
2930 // to strncat and may lead to buffer overflows.
2931 unsigned PatternType = 0;
2932 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2933 // - sizeof(dst)
2934 if (referToTheSameDecl(SizeOfArg, DstArg))
2935 PatternType = 1;
2936 // - sizeof(src)
2937 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2938 PatternType = 2;
2939 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2940 if (BE->getOpcode() == BO_Sub) {
2941 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2942 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2943 // - sizeof(dst) - strlen(dst)
2944 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2945 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2946 PatternType = 1;
2947 // - sizeof(src) - (anything)
2948 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2949 PatternType = 2;
2950 }
2951 }
2952
2953 if (PatternType == 0)
2954 return;
2955
Anna Zaksafdb0412012-02-03 01:27:37 +00002956 // Generate the diagnostic.
2957 SourceLocation SL = LenArg->getLocStart();
2958 SourceRange SR = LenArg->getSourceRange();
2959 SourceManager &SM = PP.getSourceManager();
2960
2961 // If the function is defined as a builtin macro, do not show macro expansion.
2962 if (SM.isMacroArgExpansion(SL)) {
2963 SL = SM.getSpellingLoc(SL);
2964 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2965 SM.getSpellingLoc(SR.getEnd()));
2966 }
2967
Anna Zaksc36bedc2012-02-01 19:08:57 +00002968 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002969 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002970 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002971 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002972
2973 // Output a FIXIT hint if the destination is an array (rather than a
2974 // pointer to an array). This could be enhanced to handle some
2975 // pointers if we know the actual size, like if DstArg is 'array+2'
2976 // we could say 'sizeof(array)-2'.
2977 QualType DstArgTy = DstArg->getType();
2978
2979 // Only handle constant-sized or VLAs, but not flexible members.
2980 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2981 // Only issue the FIXIT for arrays of size > 1.
2982 if (CAT->getSize().getSExtValue() <= 1)
2983 return;
2984 } else if (!DstArgTy->isVariableArrayType()) {
2985 return;
2986 }
2987
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002988 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002989 llvm::raw_svector_ostream OS(sizeString);
2990 OS << "sizeof(";
2991 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2992 OS << ") - ";
2993 OS << "strlen(";
2994 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2995 OS << ") - 1";
2996
Anna Zaksafdb0412012-02-03 01:27:37 +00002997 Diag(SL, diag::note_strncat_wrong_size)
2998 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00002999}
3000
Ted Kremenek06de2762007-08-17 16:46:58 +00003001//===--- CHECK: Return Address of Stack Variable --------------------------===//
3002
Chris Lattner5f9e2722011-07-23 10:55:15 +00003003static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
3004static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003005
3006/// CheckReturnStackAddr - Check if a return statement returns the address
3007/// of a stack variable.
3008void
3009Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3010 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003011
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003012 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003013 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003014
3015 // Perform checking for returned stack addresses, local blocks,
3016 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003017 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003018 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003019 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003020 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003021 stackE = EvalVal(RetValExp, refVars);
3022 }
3023
3024 if (stackE == 0)
3025 return; // Nothing suspicious was found.
3026
3027 SourceLocation diagLoc;
3028 SourceRange diagRange;
3029 if (refVars.empty()) {
3030 diagLoc = stackE->getLocStart();
3031 diagRange = stackE->getSourceRange();
3032 } else {
3033 // We followed through a reference variable. 'stackE' contains the
3034 // problematic expression but we will warn at the return statement pointing
3035 // at the reference variable. We will later display the "trail" of
3036 // reference variables using notes.
3037 diagLoc = refVars[0]->getLocStart();
3038 diagRange = refVars[0]->getSourceRange();
3039 }
3040
3041 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3042 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3043 : diag::warn_ret_stack_addr)
3044 << DR->getDecl()->getDeclName() << diagRange;
3045 } else if (isa<BlockExpr>(stackE)) { // local block.
3046 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3047 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3048 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3049 } else { // local temporary.
3050 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3051 : diag::warn_ret_local_temp_addr)
3052 << diagRange;
3053 }
3054
3055 // Display the "trail" of reference variables that we followed until we
3056 // found the problematic expression using notes.
3057 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3058 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3059 // If this var binds to another reference var, show the range of the next
3060 // var, otherwise the var binds to the problematic expression, in which case
3061 // show the range of the expression.
3062 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3063 : stackE->getSourceRange();
3064 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3065 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003066 }
3067}
3068
3069/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3070/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003071/// to a location on the stack, a local block, an address of a label, or a
3072/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003073/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003074/// encounter a subexpression that (1) clearly does not lead to one of the
3075/// above problematic expressions (2) is something we cannot determine leads to
3076/// a problematic expression based on such local checking.
3077///
3078/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3079/// the expression that they point to. Such variables are added to the
3080/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003081///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003082/// EvalAddr processes expressions that are pointers that are used as
3083/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003084/// At the base case of the recursion is a check for the above problematic
3085/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003086///
3087/// This implementation handles:
3088///
3089/// * pointer-to-pointer casts
3090/// * implicit conversions from array references to pointers
3091/// * taking the address of fields
3092/// * arbitrary interplay between "&" and "*" operators
3093/// * pointer arithmetic from an address of a stack variable
3094/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00003095static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003096 if (E->isTypeDependent())
3097 return NULL;
3098
Ted Kremenek06de2762007-08-17 16:46:58 +00003099 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003100 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003101 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003102 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003103 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Peter Collingbournef111d932011-04-15 00:35:48 +00003105 E = E->IgnoreParens();
3106
Ted Kremenek06de2762007-08-17 16:46:58 +00003107 // Our "symbolic interpreter" is just a dispatch off the currently
3108 // viewed AST node. We then recursively traverse the AST by calling
3109 // EvalAddr and EvalVal appropriately.
3110 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003111 case Stmt::DeclRefExprClass: {
3112 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3113
3114 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3115 // If this is a reference variable, follow through to the expression that
3116 // it points to.
3117 if (V->hasLocalStorage() &&
3118 V->getType()->isReferenceType() && V->hasInit()) {
3119 // Add the reference variable to the "trail".
3120 refVars.push_back(DR);
3121 return EvalAddr(V->getInit(), refVars);
3122 }
3123
3124 return NULL;
3125 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003126
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003127 case Stmt::UnaryOperatorClass: {
3128 // The only unary operator that make sense to handle here
3129 // is AddrOf. All others don't make sense as pointers.
3130 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003131
John McCall2de56d12010-08-25 11:45:40 +00003132 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003133 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003134 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003135 return NULL;
3136 }
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003138 case Stmt::BinaryOperatorClass: {
3139 // Handle pointer arithmetic. All other binary operators are not valid
3140 // in this context.
3141 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003142 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003143
John McCall2de56d12010-08-25 11:45:40 +00003144 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003145 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003147 Expr *Base = B->getLHS();
3148
3149 // Determine which argument is the real pointer base. It could be
3150 // the RHS argument instead of the LHS.
3151 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003153 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003154 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003155 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003156
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003157 // For conditional operators we need to see if either the LHS or RHS are
3158 // valid DeclRefExpr*s. If one of them is valid, we return it.
3159 case Stmt::ConditionalOperatorClass: {
3160 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003162 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003163 if (Expr *lhsExpr = C->getLHS()) {
3164 // In C++, we can have a throw-expression, which has 'void' type.
3165 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003166 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003167 return LHS;
3168 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003169
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003170 // In C++, we can have a throw-expression, which has 'void' type.
3171 if (C->getRHS()->getType()->isVoidType())
3172 return NULL;
3173
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003174 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003175 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003176
3177 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003178 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003179 return E; // local block.
3180 return NULL;
3181
3182 case Stmt::AddrLabelExprClass:
3183 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003184
John McCall80ee6e82011-11-10 05:35:25 +00003185 case Stmt::ExprWithCleanupsClass:
3186 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3187
Ted Kremenek54b52742008-08-07 00:49:01 +00003188 // For casts, we need to handle conversions from arrays to
3189 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003190 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003191 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003192 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003193 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003194 case Stmt::CXXStaticCastExprClass:
3195 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003196 case Stmt::CXXConstCastExprClass:
3197 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003198 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3199 switch (cast<CastExpr>(E)->getCastKind()) {
3200 case CK_BitCast:
3201 case CK_LValueToRValue:
3202 case CK_NoOp:
3203 case CK_BaseToDerived:
3204 case CK_DerivedToBase:
3205 case CK_UncheckedDerivedToBase:
3206 case CK_Dynamic:
3207 case CK_CPointerToObjCPointerCast:
3208 case CK_BlockPointerToObjCPointerCast:
3209 case CK_AnyPointerToBlockPointerCast:
3210 return EvalAddr(SubExpr, refVars);
3211
3212 case CK_ArrayToPointerDecay:
3213 return EvalVal(SubExpr, refVars);
3214
3215 default:
3216 return 0;
3217 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003218 }
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Douglas Gregor03e80032011-06-21 17:03:29 +00003220 case Stmt::MaterializeTemporaryExprClass:
3221 if (Expr *Result = EvalAddr(
3222 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3223 refVars))
3224 return Result;
3225
3226 return E;
3227
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003228 // Everything else: we simply don't reason about them.
3229 default:
3230 return NULL;
3231 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003232}
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Ted Kremenek06de2762007-08-17 16:46:58 +00003234
3235/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3236/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003237static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003238do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003239 // We should only be called for evaluating non-pointer expressions, or
3240 // expressions with a pointer type that are not used as references but instead
3241 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003242
Ted Kremenek06de2762007-08-17 16:46:58 +00003243 // Our "symbolic interpreter" is just a dispatch off the currently
3244 // viewed AST node. We then recursively traverse the AST by calling
3245 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003246
3247 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003248 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003249 case Stmt::ImplicitCastExprClass: {
3250 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003251 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003252 E = IE->getSubExpr();
3253 continue;
3254 }
3255 return NULL;
3256 }
3257
John McCall80ee6e82011-11-10 05:35:25 +00003258 case Stmt::ExprWithCleanupsClass:
3259 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3260
Douglas Gregora2813ce2009-10-23 18:54:35 +00003261 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003262 // When we hit a DeclRefExpr we are looking at code that refers to a
3263 // variable's name. If it's not a reference variable we check if it has
3264 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003265 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Ted Kremenek06de2762007-08-17 16:46:58 +00003267 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003268 if (V->hasLocalStorage()) {
3269 if (!V->getType()->isReferenceType())
3270 return DR;
3271
3272 // Reference variable, follow through to the expression that
3273 // it points to.
3274 if (V->hasInit()) {
3275 // Add the reference variable to the "trail".
3276 refVars.push_back(DR);
3277 return EvalVal(V->getInit(), refVars);
3278 }
3279 }
Mike Stump1eb44332009-09-09 15:08:12 +00003280
Ted Kremenek06de2762007-08-17 16:46:58 +00003281 return NULL;
3282 }
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Ted Kremenek06de2762007-08-17 16:46:58 +00003284 case Stmt::UnaryOperatorClass: {
3285 // The only unary operator that make sense to handle here
3286 // is Deref. All others don't resolve to a "name." This includes
3287 // handling all sorts of rvalues passed to a unary operator.
3288 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003289
John McCall2de56d12010-08-25 11:45:40 +00003290 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003291 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003292
3293 return NULL;
3294 }
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Ted Kremenek06de2762007-08-17 16:46:58 +00003296 case Stmt::ArraySubscriptExprClass: {
3297 // Array subscripts are potential references to data on the stack. We
3298 // retrieve the DeclRefExpr* for the array variable if it indeed
3299 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003300 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003301 }
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Ted Kremenek06de2762007-08-17 16:46:58 +00003303 case Stmt::ConditionalOperatorClass: {
3304 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003305 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003306 ConditionalOperator *C = cast<ConditionalOperator>(E);
3307
Anders Carlsson39073232007-11-30 19:04:31 +00003308 // Handle the GNU extension for missing LHS.
3309 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003310 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003311 return LHS;
3312
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003313 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003314 }
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Ted Kremenek06de2762007-08-17 16:46:58 +00003316 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003317 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003318 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Ted Kremenek06de2762007-08-17 16:46:58 +00003320 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003321 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003322 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003323
3324 // Check whether the member type is itself a reference, in which case
3325 // we're not going to refer to the member, but to what the member refers to.
3326 if (M->getMemberDecl()->getType()->isReferenceType())
3327 return NULL;
3328
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003329 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregor03e80032011-06-21 17:03:29 +00003332 case Stmt::MaterializeTemporaryExprClass:
3333 if (Expr *Result = EvalVal(
3334 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3335 refVars))
3336 return Result;
3337
3338 return E;
3339
Ted Kremenek06de2762007-08-17 16:46:58 +00003340 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003341 // Check that we don't return or take the address of a reference to a
3342 // temporary. This is only useful in C++.
3343 if (!E->isTypeDependent() && E->isRValue())
3344 return E;
3345
3346 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003347 return NULL;
3348 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003349} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003350}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003351
3352//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3353
3354/// Check for comparisons of floating point operands using != and ==.
3355/// Issue a warning if these are no self-comparisons, as they are not likely
3356/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003357void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003358 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Richard Trieudd225092011-09-15 21:56:47 +00003360 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3361 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003362
3363 // Special case: check for x == x (which is OK).
3364 // Do not emit warnings for such cases.
3365 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3366 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3367 if (DRL->getDecl() == DRR->getDecl())
3368 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003369
3370
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003371 // Special case: check for comparisons against literals that can be exactly
3372 // represented by APFloat. In such cases, do not emit a warning. This
3373 // is a heuristic: often comparison against such literals are used to
3374 // detect if a value in a variable has not changed. This clearly can
3375 // lead to false negatives.
3376 if (EmitWarning) {
3377 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3378 if (FLL->isExact())
3379 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003380 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003381 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3382 if (FLR->isExact())
3383 EmitWarning = false;
3384 }
3385 }
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003387 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003388 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003389 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003390 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003391 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Sebastian Redl0eb23302009-01-19 00:08:26 +00003393 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003394 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003395 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003396 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003398 // Emit the diagnostic.
3399 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003400 Diag(Loc, diag::warn_floatingpoint_eq)
3401 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003402}
John McCallba26e582010-01-04 23:21:16 +00003403
John McCallf2370c92010-01-06 05:24:50 +00003404//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3405//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003406
John McCallf2370c92010-01-06 05:24:50 +00003407namespace {
John McCallba26e582010-01-04 23:21:16 +00003408
John McCallf2370c92010-01-06 05:24:50 +00003409/// Structure recording the 'active' range of an integer-valued
3410/// expression.
3411struct IntRange {
3412 /// The number of bits active in the int.
3413 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003414
John McCallf2370c92010-01-06 05:24:50 +00003415 /// True if the int is known not to have negative values.
3416 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003417
John McCallf2370c92010-01-06 05:24:50 +00003418 IntRange(unsigned Width, bool NonNegative)
3419 : Width(Width), NonNegative(NonNegative)
3420 {}
John McCallba26e582010-01-04 23:21:16 +00003421
John McCall1844a6e2010-11-10 23:38:19 +00003422 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003423 static IntRange forBoolType() {
3424 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003425 }
3426
John McCall1844a6e2010-11-10 23:38:19 +00003427 /// Returns the range of an opaque value of the given integral type.
3428 static IntRange forValueOfType(ASTContext &C, QualType T) {
3429 return forValueOfCanonicalType(C,
3430 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003431 }
3432
John McCall1844a6e2010-11-10 23:38:19 +00003433 /// Returns the range of an opaque value of a canonical integral type.
3434 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003435 assert(T->isCanonicalUnqualified());
3436
3437 if (const VectorType *VT = dyn_cast<VectorType>(T))
3438 T = VT->getElementType().getTypePtr();
3439 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3440 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003441
John McCall091f23f2010-11-09 22:22:12 +00003442 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003443 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3444 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003445 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003446 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3447
John McCall323ed742010-05-06 08:58:33 +00003448 unsigned NumPositive = Enum->getNumPositiveBits();
3449 unsigned NumNegative = Enum->getNumNegativeBits();
3450
3451 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3452 }
John McCallf2370c92010-01-06 05:24:50 +00003453
3454 const BuiltinType *BT = cast<BuiltinType>(T);
3455 assert(BT->isInteger());
3456
3457 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3458 }
3459
John McCall1844a6e2010-11-10 23:38:19 +00003460 /// Returns the "target" range of a canonical integral type, i.e.
3461 /// the range of values expressible in the type.
3462 ///
3463 /// This matches forValueOfCanonicalType except that enums have the
3464 /// full range of their type, not the range of their enumerators.
3465 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3466 assert(T->isCanonicalUnqualified());
3467
3468 if (const VectorType *VT = dyn_cast<VectorType>(T))
3469 T = VT->getElementType().getTypePtr();
3470 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3471 T = CT->getElementType().getTypePtr();
3472 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003473 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003474
3475 const BuiltinType *BT = cast<BuiltinType>(T);
3476 assert(BT->isInteger());
3477
3478 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3479 }
3480
3481 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003482 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003483 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003484 L.NonNegative && R.NonNegative);
3485 }
3486
John McCall1844a6e2010-11-10 23:38:19 +00003487 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003488 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003489 return IntRange(std::min(L.Width, R.Width),
3490 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003491 }
3492};
3493
Ted Kremenek0692a192012-01-31 05:37:37 +00003494static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3495 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003496 if (value.isSigned() && value.isNegative())
3497 return IntRange(value.getMinSignedBits(), false);
3498
3499 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003500 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003501
3502 // isNonNegative() just checks the sign bit without considering
3503 // signedness.
3504 return IntRange(value.getActiveBits(), true);
3505}
3506
Ted Kremenek0692a192012-01-31 05:37:37 +00003507static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3508 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003509 if (result.isInt())
3510 return GetValueRange(C, result.getInt(), MaxWidth);
3511
3512 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003513 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3514 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3515 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3516 R = IntRange::join(R, El);
3517 }
John McCallf2370c92010-01-06 05:24:50 +00003518 return R;
3519 }
3520
3521 if (result.isComplexInt()) {
3522 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3523 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3524 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003525 }
3526
3527 // This can happen with lossless casts to intptr_t of "based" lvalues.
3528 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003529 // FIXME: The only reason we need to pass the type in here is to get
3530 // the sign right on this one case. It would be nice if APValue
3531 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003532 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003533 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003534}
John McCallf2370c92010-01-06 05:24:50 +00003535
3536/// Pseudo-evaluate the given integer expression, estimating the
3537/// range of values it might take.
3538///
3539/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003540static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003541 E = E->IgnoreParens();
3542
3543 // Try a full evaluation first.
3544 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003545 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003546 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003547
3548 // I think we only want to look through implicit casts here; if the
3549 // user has an explicit widening cast, we should treat the value as
3550 // being of the new, wider type.
3551 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003552 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003553 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3554
John McCall1844a6e2010-11-10 23:38:19 +00003555 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003556
John McCall2de56d12010-08-25 11:45:40 +00003557 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003558
John McCallf2370c92010-01-06 05:24:50 +00003559 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003560 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003561 return OutputTypeRange;
3562
3563 IntRange SubRange
3564 = GetExprRange(C, CE->getSubExpr(),
3565 std::min(MaxWidth, OutputTypeRange.Width));
3566
3567 // Bail out if the subexpr's range is as wide as the cast type.
3568 if (SubRange.Width >= OutputTypeRange.Width)
3569 return OutputTypeRange;
3570
3571 // Otherwise, we take the smaller width, and we're non-negative if
3572 // either the output type or the subexpr is.
3573 return IntRange(SubRange.Width,
3574 SubRange.NonNegative || OutputTypeRange.NonNegative);
3575 }
3576
3577 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3578 // If we can fold the condition, just take that operand.
3579 bool CondResult;
3580 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3581 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3582 : CO->getFalseExpr(),
3583 MaxWidth);
3584
3585 // Otherwise, conservatively merge.
3586 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3587 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3588 return IntRange::join(L, R);
3589 }
3590
3591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3592 switch (BO->getOpcode()) {
3593
3594 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003595 case BO_LAnd:
3596 case BO_LOr:
3597 case BO_LT:
3598 case BO_GT:
3599 case BO_LE:
3600 case BO_GE:
3601 case BO_EQ:
3602 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003603 return IntRange::forBoolType();
3604
John McCall862ff872011-07-13 06:35:24 +00003605 // The type of the assignments is the type of the LHS, so the RHS
3606 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003607 case BO_MulAssign:
3608 case BO_DivAssign:
3609 case BO_RemAssign:
3610 case BO_AddAssign:
3611 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003612 case BO_XorAssign:
3613 case BO_OrAssign:
3614 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003615 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003616
John McCall862ff872011-07-13 06:35:24 +00003617 // Simple assignments just pass through the RHS, which will have
3618 // been coerced to the LHS type.
3619 case BO_Assign:
3620 // TODO: bitfields?
3621 return GetExprRange(C, BO->getRHS(), MaxWidth);
3622
John McCallf2370c92010-01-06 05:24:50 +00003623 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003624 case BO_PtrMemD:
3625 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003626 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003627
John McCall60fad452010-01-06 22:07:33 +00003628 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003629 case BO_And:
3630 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003631 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3632 GetExprRange(C, BO->getRHS(), MaxWidth));
3633
John McCallf2370c92010-01-06 05:24:50 +00003634 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003635 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003636 // ...except that we want to treat '1 << (blah)' as logically
3637 // positive. It's an important idiom.
3638 if (IntegerLiteral *I
3639 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3640 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003641 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003642 return IntRange(R.Width, /*NonNegative*/ true);
3643 }
3644 }
3645 // fallthrough
3646
John McCall2de56d12010-08-25 11:45:40 +00003647 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003648 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003649
John McCall60fad452010-01-06 22:07:33 +00003650 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003651 case BO_Shr:
3652 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003653 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3654
3655 // If the shift amount is a positive constant, drop the width by
3656 // that much.
3657 llvm::APSInt shift;
3658 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3659 shift.isNonNegative()) {
3660 unsigned zext = shift.getZExtValue();
3661 if (zext >= L.Width)
3662 L.Width = (L.NonNegative ? 0 : 1);
3663 else
3664 L.Width -= zext;
3665 }
3666
3667 return L;
3668 }
3669
3670 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003671 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003672 return GetExprRange(C, BO->getRHS(), MaxWidth);
3673
John McCall60fad452010-01-06 22:07:33 +00003674 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003675 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003676 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003677 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003678 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003679
John McCall00fe7612011-07-14 22:39:48 +00003680 // The width of a division result is mostly determined by the size
3681 // of the LHS.
3682 case BO_Div: {
3683 // Don't 'pre-truncate' the operands.
3684 unsigned opWidth = C.getIntWidth(E->getType());
3685 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3686
3687 // If the divisor is constant, use that.
3688 llvm::APSInt divisor;
3689 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3690 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3691 if (log2 >= L.Width)
3692 L.Width = (L.NonNegative ? 0 : 1);
3693 else
3694 L.Width = std::min(L.Width - log2, MaxWidth);
3695 return L;
3696 }
3697
3698 // Otherwise, just use the LHS's width.
3699 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3700 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3701 }
3702
3703 // The result of a remainder can't be larger than the result of
3704 // either side.
3705 case BO_Rem: {
3706 // Don't 'pre-truncate' the operands.
3707 unsigned opWidth = C.getIntWidth(E->getType());
3708 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3709 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3710
3711 IntRange meet = IntRange::meet(L, R);
3712 meet.Width = std::min(meet.Width, MaxWidth);
3713 return meet;
3714 }
3715
3716 // The default behavior is okay for these.
3717 case BO_Mul:
3718 case BO_Add:
3719 case BO_Xor:
3720 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003721 break;
3722 }
3723
John McCall00fe7612011-07-14 22:39:48 +00003724 // The default case is to treat the operation as if it were closed
3725 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003726 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3727 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3728 return IntRange::join(L, R);
3729 }
3730
3731 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3732 switch (UO->getOpcode()) {
3733 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003734 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003735 return IntRange::forBoolType();
3736
3737 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003738 case UO_Deref:
3739 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003740 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003741
3742 default:
3743 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3744 }
3745 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003746
3747 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003748 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003749 }
John McCallf2370c92010-01-06 05:24:50 +00003750
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003751 if (FieldDecl *BitField = E->getBitField())
3752 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003753 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003754
John McCall1844a6e2010-11-10 23:38:19 +00003755 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003756}
John McCall51313c32010-01-04 23:31:57 +00003757
Ted Kremenek0692a192012-01-31 05:37:37 +00003758static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003759 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3760}
3761
John McCall51313c32010-01-04 23:31:57 +00003762/// Checks whether the given value, which currently has the given
3763/// source semantics, has the same value when coerced through the
3764/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003765static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3766 const llvm::fltSemantics &Src,
3767 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003768 llvm::APFloat truncated = value;
3769
3770 bool ignored;
3771 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3772 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3773
3774 return truncated.bitwiseIsEqual(value);
3775}
3776
3777/// Checks whether the given value, which currently has the given
3778/// source semantics, has the same value when coerced through the
3779/// target semantics.
3780///
3781/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003782static bool IsSameFloatAfterCast(const APValue &value,
3783 const llvm::fltSemantics &Src,
3784 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003785 if (value.isFloat())
3786 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3787
3788 if (value.isVector()) {
3789 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3790 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3791 return false;
3792 return true;
3793 }
3794
3795 assert(value.isComplexFloat());
3796 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3797 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3798}
3799
Ted Kremenek0692a192012-01-31 05:37:37 +00003800static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003801
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003802static bool IsZero(Sema &S, Expr *E) {
3803 // Suppress cases where we are comparing against an enum constant.
3804 if (const DeclRefExpr *DR =
3805 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3806 if (isa<EnumConstantDecl>(DR->getDecl()))
3807 return false;
3808
3809 // Suppress cases where the '0' value is expanded from a macro.
3810 if (E->getLocStart().isMacroID())
3811 return false;
3812
John McCall323ed742010-05-06 08:58:33 +00003813 llvm::APSInt Value;
3814 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3815}
3816
John McCall372e1032010-10-06 00:25:24 +00003817static bool HasEnumType(Expr *E) {
3818 // Strip off implicit integral promotions.
3819 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003820 if (ICE->getCastKind() != CK_IntegralCast &&
3821 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003822 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003823 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003824 }
3825
3826 return E->getType()->isEnumeralType();
3827}
3828
Ted Kremenek0692a192012-01-31 05:37:37 +00003829static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003830 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003831 if (E->isValueDependent())
3832 return;
3833
John McCall2de56d12010-08-25 11:45:40 +00003834 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003835 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003836 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003837 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003838 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003839 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003840 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003841 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003842 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003843 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003844 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003845 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003846 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003847 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003848 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003849 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3850 }
3851}
3852
3853/// Analyze the operands of the given comparison. Implements the
3854/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003855static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003856 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3857 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003858}
John McCall51313c32010-01-04 23:31:57 +00003859
John McCallba26e582010-01-04 23:21:16 +00003860/// \brief Implements -Wsign-compare.
3861///
Richard Trieudd225092011-09-15 21:56:47 +00003862/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003863static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003864 // The type the comparison is being performed in.
3865 QualType T = E->getLHS()->getType();
3866 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3867 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003868
John McCall323ed742010-05-06 08:58:33 +00003869 // We don't do anything special if this isn't an unsigned integral
3870 // comparison: we're only interested in integral comparisons, and
3871 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003872 //
3873 // We also don't care about value-dependent expressions or expressions
3874 // whose result is a constant.
3875 if (!T->hasUnsignedIntegerRepresentation()
3876 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003877 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003878
Richard Trieudd225092011-09-15 21:56:47 +00003879 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3880 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003881
John McCall323ed742010-05-06 08:58:33 +00003882 // Check to see if one of the (unmodified) operands is of different
3883 // signedness.
3884 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003885 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3886 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003887 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003888 signedOperand = LHS;
3889 unsignedOperand = RHS;
3890 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3891 signedOperand = RHS;
3892 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003893 } else {
John McCall323ed742010-05-06 08:58:33 +00003894 CheckTrivialUnsignedComparison(S, E);
3895 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003896 }
3897
John McCall323ed742010-05-06 08:58:33 +00003898 // Otherwise, calculate the effective range of the signed operand.
3899 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003900
John McCall323ed742010-05-06 08:58:33 +00003901 // Go ahead and analyze implicit conversions in the operands. Note
3902 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003903 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3904 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003905
John McCall323ed742010-05-06 08:58:33 +00003906 // If the signed range is non-negative, -Wsign-compare won't fire,
3907 // but we should still check for comparisons which are always true
3908 // or false.
3909 if (signedRange.NonNegative)
3910 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003911
3912 // For (in)equality comparisons, if the unsigned operand is a
3913 // constant which cannot collide with a overflowed signed operand,
3914 // then reinterpreting the signed operand as unsigned will not
3915 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003916 if (E->isEqualityOp()) {
3917 unsigned comparisonWidth = S.Context.getIntWidth(T);
3918 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003919
John McCall323ed742010-05-06 08:58:33 +00003920 // We should never be unable to prove that the unsigned operand is
3921 // non-negative.
3922 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3923
3924 if (unsignedRange.Width < comparisonWidth)
3925 return;
3926 }
3927
3928 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003929 << LHS->getType() << RHS->getType()
3930 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003931}
3932
John McCall15d7d122010-11-11 03:21:53 +00003933/// Analyzes an attempt to assign the given value to a bitfield.
3934///
3935/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003936static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3937 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003938 assert(Bitfield->isBitField());
3939 if (Bitfield->isInvalidDecl())
3940 return false;
3941
John McCall91b60142010-11-11 05:33:51 +00003942 // White-list bool bitfields.
3943 if (Bitfield->getType()->isBooleanType())
3944 return false;
3945
Douglas Gregor46ff3032011-02-04 13:09:01 +00003946 // Ignore value- or type-dependent expressions.
3947 if (Bitfield->getBitWidth()->isValueDependent() ||
3948 Bitfield->getBitWidth()->isTypeDependent() ||
3949 Init->isValueDependent() ||
3950 Init->isTypeDependent())
3951 return false;
3952
John McCall15d7d122010-11-11 03:21:53 +00003953 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3954
Richard Smith80d4b552011-12-28 19:48:30 +00003955 llvm::APSInt Value;
3956 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003957 return false;
3958
John McCall15d7d122010-11-11 03:21:53 +00003959 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003960 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003961
3962 if (OriginalWidth <= FieldWidth)
3963 return false;
3964
Eli Friedman3a643af2012-01-26 23:11:39 +00003965 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003966 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003967 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003968
Eli Friedman3a643af2012-01-26 23:11:39 +00003969 // Check whether the stored value is equal to the original value.
3970 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003971 if (Value == TruncatedValue)
3972 return false;
3973
Eli Friedman3a643af2012-01-26 23:11:39 +00003974 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00003975 // therefore don't strictly fit into a signed bitfield of width 1.
3976 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00003977 return false;
3978
John McCall15d7d122010-11-11 03:21:53 +00003979 std::string PrettyValue = Value.toString(10);
3980 std::string PrettyTrunc = TruncatedValue.toString(10);
3981
3982 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3983 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3984 << Init->getSourceRange();
3985
3986 return true;
3987}
3988
John McCallbeb22aa2010-11-09 23:24:47 +00003989/// Analyze the given simple or compound assignment for warning-worthy
3990/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00003991static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00003992 // Just recurse on the LHS.
3993 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3994
3995 // We want to recurse on the RHS as normal unless we're assigning to
3996 // a bitfield.
3997 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003998 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3999 E->getOperatorLoc())) {
4000 // Recurse, ignoring any implicit conversions on the RHS.
4001 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4002 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004003 }
4004 }
4005
4006 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4007}
4008
John McCall51313c32010-01-04 23:31:57 +00004009/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004010static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004011 SourceLocation CContext, unsigned diag,
4012 bool pruneControlFlow = false) {
4013 if (pruneControlFlow) {
4014 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4015 S.PDiag(diag)
4016 << SourceType << T << E->getSourceRange()
4017 << SourceRange(CContext));
4018 return;
4019 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004020 S.Diag(E->getExprLoc(), diag)
4021 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4022}
4023
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004024/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004025static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004026 SourceLocation CContext, unsigned diag,
4027 bool pruneControlFlow = false) {
4028 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004029}
4030
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004031/// Diagnose an implicit cast from a literal expression. Does not warn when the
4032/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004033void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4034 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004035 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004036 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004037 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004038 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4039 T->hasUnsignedIntegerRepresentation());
4040 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004041 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004042 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004043 return;
4044
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004045 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
4046 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004047}
4048
John McCall091f23f2010-11-09 22:22:12 +00004049std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4050 if (!Range.Width) return "0";
4051
4052 llvm::APSInt ValueInRange = Value;
4053 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004054 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004055 return ValueInRange.toString(10);
4056}
4057
John McCall323ed742010-05-06 08:58:33 +00004058void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004059 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004060 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004061
John McCall323ed742010-05-06 08:58:33 +00004062 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4063 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4064 if (Source == Target) return;
4065 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004066
Chandler Carruth108f7562011-07-26 05:40:03 +00004067 // If the conversion context location is invalid don't complain. We also
4068 // don't want to emit a warning if the issue occurs from the expansion of
4069 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4070 // delay this check as long as possible. Once we detect we are in that
4071 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004072 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004073 return;
4074
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004075 // Diagnose implicit casts to bool.
4076 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4077 if (isa<StringLiteral>(E))
4078 // Warn on string literal to bool. Checks for string literals in logical
4079 // expressions, for instances, assert(0 && "error here"), is prevented
4080 // by a check in AnalyzeImplicitConversions().
4081 return DiagnoseImpCast(S, E, T, CC,
4082 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004083 if (Source->isFunctionType()) {
4084 // Warn on function to bool. Checks free functions and static member
4085 // functions. Weakly imported functions are excluded from the check,
4086 // since it's common to test their value to check whether the linker
4087 // found a definition for them.
4088 ValueDecl *D = 0;
4089 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4090 D = R->getDecl();
4091 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4092 D = M->getMemberDecl();
4093 }
4094
4095 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004096 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4097 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4098 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004099 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4100 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4101 QualType ReturnType;
4102 UnresolvedSet<4> NonTemplateOverloads;
4103 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4104 if (!ReturnType.isNull()
4105 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4106 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4107 << FixItHint::CreateInsertion(
4108 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004109 return;
4110 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004111 }
4112 }
David Blaikiee37cdc42011-09-29 04:06:47 +00004113 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004114 }
John McCall51313c32010-01-04 23:31:57 +00004115
4116 // Strip vector types.
4117 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004118 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004119 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004120 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004121 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004122 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004123
4124 // If the vector cast is cast between two vectors of the same size, it is
4125 // a bitcast, not a conversion.
4126 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4127 return;
John McCall51313c32010-01-04 23:31:57 +00004128
4129 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4130 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4131 }
4132
4133 // Strip complex types.
4134 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004135 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004136 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004137 return;
4138
John McCallb4eb64d2010-10-08 02:01:28 +00004139 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004140 }
John McCall51313c32010-01-04 23:31:57 +00004141
4142 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4143 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4144 }
4145
4146 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4147 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4148
4149 // If the source is floating point...
4150 if (SourceBT && SourceBT->isFloatingPoint()) {
4151 // ...and the target is floating point...
4152 if (TargetBT && TargetBT->isFloatingPoint()) {
4153 // ...then warn if we're dropping FP rank.
4154
4155 // Builtin FP kinds are ordered by increasing FP rank.
4156 if (SourceBT->getKind() > TargetBT->getKind()) {
4157 // Don't warn about float constants that are precisely
4158 // representable in the target type.
4159 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004160 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004161 // Value might be a float, a float vector, or a float complex.
4162 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004163 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4164 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004165 return;
4166 }
4167
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004168 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004169 return;
4170
John McCallb4eb64d2010-10-08 02:01:28 +00004171 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004172 }
4173 return;
4174 }
4175
Ted Kremenekef9ff882011-03-10 20:03:42 +00004176 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00004177 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004178 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004179 return;
4180
Chandler Carrutha5b93322011-02-17 11:05:49 +00004181 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004182 // We also want to warn on, e.g., "int i = -1.234"
4183 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4184 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4185 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4186
Chandler Carruthf65076e2011-04-10 08:36:24 +00004187 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4188 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004189 } else {
4190 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4191 }
4192 }
John McCall51313c32010-01-04 23:31:57 +00004193
4194 return;
4195 }
4196
John McCallf2370c92010-01-06 05:24:50 +00004197 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004198 return;
4199
Richard Trieu1838ca52011-05-29 19:59:02 +00004200 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4201 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004202 SourceLocation Loc = E->getSourceRange().getBegin();
4203 if (Loc.isMacroID())
4204 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4205 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4206 << T << Loc << clang::SourceRange(CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00004207 return;
4208 }
4209
John McCall323ed742010-05-06 08:58:33 +00004210 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004211 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004212
4213 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004214 // If the source is a constant, use a default-on diagnostic.
4215 // TODO: this should happen for bitfield stores, too.
4216 llvm::APSInt Value(32);
4217 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004218 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004219 return;
4220
John McCall091f23f2010-11-09 22:22:12 +00004221 std::string PrettySourceValue = Value.toString(10);
4222 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4223
Ted Kremenek5e745da2011-10-22 02:37:33 +00004224 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4225 S.PDiag(diag::warn_impcast_integer_precision_constant)
4226 << PrettySourceValue << PrettyTargetValue
4227 << E->getType() << T << E->getSourceRange()
4228 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004229 return;
4230 }
4231
Chris Lattnerb792b302011-06-14 04:51:15 +00004232 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004233 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004234 return;
4235
John McCallf2370c92010-01-06 05:24:50 +00004236 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004237 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4238 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004239 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004240 }
4241
4242 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4243 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4244 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004245
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004246 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004247 return;
4248
John McCall323ed742010-05-06 08:58:33 +00004249 unsigned DiagID = diag::warn_impcast_integer_sign;
4250
4251 // Traditionally, gcc has warned about this under -Wsign-compare.
4252 // We also want to warn about it in -Wconversion.
4253 // So if -Wconversion is off, use a completely identical diagnostic
4254 // in the sign-compare group.
4255 // The conditional-checking code will
4256 if (ICContext) {
4257 DiagID = diag::warn_impcast_integer_sign_conditional;
4258 *ICContext = true;
4259 }
4260
John McCallb4eb64d2010-10-08 02:01:28 +00004261 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004262 }
4263
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004264 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004265 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4266 // type, to give us better diagnostics.
4267 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004268 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004269 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4270 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4271 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4272 SourceType = S.Context.getTypeDeclType(Enum);
4273 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4274 }
4275 }
4276
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004277 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4278 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4279 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004280 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004281 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004282 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004283 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004284 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004285 return;
4286
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004287 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004288 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004289 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004290
John McCall51313c32010-01-04 23:31:57 +00004291 return;
4292}
4293
John McCall323ed742010-05-06 08:58:33 +00004294void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4295
4296void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004297 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004298 E = E->IgnoreParenImpCasts();
4299
4300 if (isa<ConditionalOperator>(E))
4301 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4302
John McCallb4eb64d2010-10-08 02:01:28 +00004303 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004304 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004305 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004306 return;
4307}
4308
4309void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004310 SourceLocation CC = E->getQuestionLoc();
4311
4312 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004313
4314 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004315 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4316 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004317
4318 // If -Wconversion would have warned about either of the candidates
4319 // for a signedness conversion to the context type...
4320 if (!Suspicious) return;
4321
4322 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004323 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4324 CC))
John McCall323ed742010-05-06 08:58:33 +00004325 return;
4326
John McCall323ed742010-05-06 08:58:33 +00004327 // ...then check whether it would have warned about either of the
4328 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004329 if (E->getType() == T) return;
4330
4331 Suspicious = false;
4332 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4333 E->getType(), CC, &Suspicious);
4334 if (!Suspicious)
4335 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004336 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004337}
4338
4339/// AnalyzeImplicitConversions - Find and report any interesting
4340/// implicit conversions in the given expression. There are a couple
4341/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004342void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004343 QualType T = OrigE->getType();
4344 Expr *E = OrigE->IgnoreParenImpCasts();
4345
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004346 if (E->isTypeDependent() || E->isValueDependent())
4347 return;
4348
John McCall323ed742010-05-06 08:58:33 +00004349 // For conditional operators, we analyze the arguments as if they
4350 // were being fed directly into the output.
4351 if (isa<ConditionalOperator>(E)) {
4352 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4353 CheckConditionalOperator(S, CO, T);
4354 return;
4355 }
4356
4357 // Go ahead and check any implicit conversions we might have skipped.
4358 // The non-canonical typecheck is just an optimization;
4359 // CheckImplicitConversion will filter out dead implicit conversions.
4360 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004361 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004362
4363 // Now continue drilling into this expression.
4364
4365 // Skip past explicit casts.
4366 if (isa<ExplicitCastExpr>(E)) {
4367 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004368 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004369 }
4370
John McCallbeb22aa2010-11-09 23:24:47 +00004371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4372 // Do a somewhat different check with comparison operators.
4373 if (BO->isComparisonOp())
4374 return AnalyzeComparison(S, BO);
4375
Eli Friedman0fa06382012-01-26 23:34:06 +00004376 // And with simple assignments.
4377 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004378 return AnalyzeAssignment(S, BO);
4379 }
John McCall323ed742010-05-06 08:58:33 +00004380
4381 // These break the otherwise-useful invariant below. Fortunately,
4382 // we don't really need to recurse into them, because any internal
4383 // expressions should have been analyzed already when they were
4384 // built into statements.
4385 if (isa<StmtExpr>(E)) return;
4386
4387 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004388 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004389
4390 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004391 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004392 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4393 bool IsLogicalOperator = BO && BO->isLogicalOp();
4394 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004395 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004396 if (!ChildExpr)
4397 continue;
4398
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004399 if (IsLogicalOperator &&
4400 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4401 // Ignore checking string literals that are in logical operators.
4402 continue;
4403 AnalyzeImplicitConversions(S, ChildExpr, CC);
4404 }
John McCall323ed742010-05-06 08:58:33 +00004405}
4406
4407} // end anonymous namespace
4408
4409/// Diagnoses "dangerous" implicit conversions within the given
4410/// expression (which is a full expression). Implements -Wconversion
4411/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004412///
4413/// \param CC the "context" location of the implicit conversion, i.e.
4414/// the most location of the syntactic entity requiring the implicit
4415/// conversion
4416void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004417 // Don't diagnose in unevaluated contexts.
4418 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4419 return;
4420
4421 // Don't diagnose for value- or type-dependent expressions.
4422 if (E->isTypeDependent() || E->isValueDependent())
4423 return;
4424
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004425 // Check for array bounds violations in cases where the check isn't triggered
4426 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4427 // ArraySubscriptExpr is on the RHS of a variable initialization.
4428 CheckArrayAccess(E);
4429
John McCallb4eb64d2010-10-08 02:01:28 +00004430 // This is not the right CC for (e.g.) a variable initialization.
4431 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004432}
4433
John McCall15d7d122010-11-11 03:21:53 +00004434void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4435 FieldDecl *BitField,
4436 Expr *Init) {
4437 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4438}
4439
Mike Stumpf8c49212010-01-21 03:59:47 +00004440/// CheckParmsForFunctionDef - Check that the parameters of the given
4441/// function are appropriate for the definition of a function. This
4442/// takes care of any checks that cannot be performed on the
4443/// declaration itself, e.g., that the types of each of the function
4444/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004445bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4446 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004447 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004448 for (; P != PEnd; ++P) {
4449 ParmVarDecl *Param = *P;
4450
Mike Stumpf8c49212010-01-21 03:59:47 +00004451 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4452 // function declarator that is part of a function definition of
4453 // that function shall not have incomplete type.
4454 //
4455 // This is also C++ [dcl.fct]p6.
4456 if (!Param->isInvalidDecl() &&
4457 RequireCompleteType(Param->getLocation(), Param->getType(),
4458 diag::err_typecheck_decl_incomplete_type)) {
4459 Param->setInvalidDecl();
4460 HasInvalidParm = true;
4461 }
4462
4463 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4464 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004465 if (CheckParameterNames &&
4466 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004467 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004468 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004469 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004470
4471 // C99 6.7.5.3p12:
4472 // If the function declarator is not part of a definition of that
4473 // function, parameters may have incomplete type and may use the [*]
4474 // notation in their sequences of declarator specifiers to specify
4475 // variable length array types.
4476 QualType PType = Param->getOriginalType();
4477 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4478 if (AT->getSizeModifier() == ArrayType::Star) {
4479 // FIXME: This diagnosic should point the the '[*]' if source-location
4480 // information is added for it.
4481 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4482 }
4483 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004484 }
4485
4486 return HasInvalidParm;
4487}
John McCallb7f4ffe2010-08-12 21:44:57 +00004488
4489/// CheckCastAlign - Implements -Wcast-align, which warns when a
4490/// pointer cast increases the alignment requirements.
4491void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4492 // This is actually a lot of work to potentially be doing on every
4493 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004494 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4495 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004496 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004497 return;
4498
4499 // Ignore dependent types.
4500 if (T->isDependentType() || Op->getType()->isDependentType())
4501 return;
4502
4503 // Require that the destination be a pointer type.
4504 const PointerType *DestPtr = T->getAs<PointerType>();
4505 if (!DestPtr) return;
4506
4507 // If the destination has alignment 1, we're done.
4508 QualType DestPointee = DestPtr->getPointeeType();
4509 if (DestPointee->isIncompleteType()) return;
4510 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4511 if (DestAlign.isOne()) return;
4512
4513 // Require that the source be a pointer type.
4514 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4515 if (!SrcPtr) return;
4516 QualType SrcPointee = SrcPtr->getPointeeType();
4517
4518 // Whitelist casts from cv void*. We already implicitly
4519 // whitelisted casts to cv void*, since they have alignment 1.
4520 // Also whitelist casts involving incomplete types, which implicitly
4521 // includes 'void'.
4522 if (SrcPointee->isIncompleteType()) return;
4523
4524 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4525 if (SrcAlign >= DestAlign) return;
4526
4527 Diag(TRange.getBegin(), diag::warn_cast_align)
4528 << Op->getType() << T
4529 << static_cast<unsigned>(SrcAlign.getQuantity())
4530 << static_cast<unsigned>(DestAlign.getQuantity())
4531 << TRange << Op->getSourceRange();
4532}
4533
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004534static const Type* getElementType(const Expr *BaseExpr) {
4535 const Type* EltType = BaseExpr->getType().getTypePtr();
4536 if (EltType->isAnyPointerType())
4537 return EltType->getPointeeType().getTypePtr();
4538 else if (EltType->isArrayType())
4539 return EltType->getBaseElementTypeUnsafe();
4540 return EltType;
4541}
4542
Chandler Carruthc2684342011-08-05 09:10:50 +00004543/// \brief Check whether this array fits the idiom of a size-one tail padded
4544/// array member of a struct.
4545///
4546/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4547/// commonly used to emulate flexible arrays in C89 code.
4548static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4549 const NamedDecl *ND) {
4550 if (Size != 1 || !ND) return false;
4551
4552 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4553 if (!FD) return false;
4554
4555 // Don't consider sizes resulting from macro expansions or template argument
4556 // substitution to form C89 tail-padded arrays.
4557 ConstantArrayTypeLoc TL =
4558 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4559 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4560 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4561 return false;
4562
4563 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004564 if (!RD) return false;
4565 if (RD->isUnion()) return false;
4566 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4567 if (!CRD->isStandardLayout()) return false;
4568 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004569
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004570 // See if this is the last field decl in the record.
4571 const Decl *D = FD;
4572 while ((D = D->getNextDeclInContext()))
4573 if (isa<FieldDecl>(D))
4574 return false;
4575 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004576}
4577
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004578void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004579 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004580 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004581 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004582 if (IndexExpr->isValueDependent())
4583 return;
4584
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004585 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004586 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004587 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004588 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004589 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004590 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004591
Chandler Carruth34064582011-02-17 20:55:08 +00004592 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004593 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004594 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004595 if (IndexNegated)
4596 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004597
Chandler Carruthba447122011-08-05 08:07:29 +00004598 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004599 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4600 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004601 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004602 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004603
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004604 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004605 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004606 if (!size.isStrictlyPositive())
4607 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004608
4609 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004610 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004611 // Make sure we're comparing apples to apples when comparing index to size
4612 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4613 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004614 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004615 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004616 if (ptrarith_typesize != array_typesize) {
4617 // There's a cast to a different size type involved
4618 uint64_t ratio = array_typesize / ptrarith_typesize;
4619 // TODO: Be smarter about handling cases where array_typesize is not a
4620 // multiple of ptrarith_typesize
4621 if (ptrarith_typesize * ratio == array_typesize)
4622 size *= llvm::APInt(size.getBitWidth(), ratio);
4623 }
4624 }
4625
Chandler Carruth34064582011-02-17 20:55:08 +00004626 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004627 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004628 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004629 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004630
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004631 // For array subscripting the index must be less than size, but for pointer
4632 // arithmetic also allow the index (offset) to be equal to size since
4633 // computing the next address after the end of the array is legal and
4634 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004635 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004636 return;
4637
4638 // Also don't warn for arrays of size 1 which are members of some
4639 // structure. These are often used to approximate flexible arrays in C89
4640 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004641 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004642 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004643
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004644 // Suppress the warning if the subscript expression (as identified by the
4645 // ']' location) and the index expression are both from macro expansions
4646 // within a system header.
4647 if (ASE) {
4648 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4649 ASE->getRBracketLoc());
4650 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4651 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4652 IndexExpr->getLocStart());
4653 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4654 return;
4655 }
4656 }
4657
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004658 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004659 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004660 DiagID = diag::warn_array_index_exceeds_bounds;
4661
4662 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4663 PDiag(DiagID) << index.toString(10, true)
4664 << size.toString(10, true)
4665 << (unsigned)size.getLimitedValue(~0U)
4666 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004667 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004668 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004669 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004670 DiagID = diag::warn_ptr_arith_precedes_bounds;
4671 if (index.isNegative()) index = -index;
4672 }
4673
4674 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4675 PDiag(DiagID) << index.toString(10, true)
4676 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004677 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004678
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004679 if (!ND) {
4680 // Try harder to find a NamedDecl to point at in the note.
4681 while (const ArraySubscriptExpr *ASE =
4682 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4683 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4685 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4687 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4688 }
4689
Chandler Carruth35001ca2011-02-17 21:10:52 +00004690 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004691 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4692 PDiag(diag::note_array_index_out_of_bounds)
4693 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004694}
4695
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004696void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004697 int AllowOnePastEnd = 0;
4698 while (expr) {
4699 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004700 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004701 case Stmt::ArraySubscriptExprClass: {
4702 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004703 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004704 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004705 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004706 }
4707 case Stmt::UnaryOperatorClass: {
4708 // Only unwrap the * and & unary operators
4709 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4710 expr = UO->getSubExpr();
4711 switch (UO->getOpcode()) {
4712 case UO_AddrOf:
4713 AllowOnePastEnd++;
4714 break;
4715 case UO_Deref:
4716 AllowOnePastEnd--;
4717 break;
4718 default:
4719 return;
4720 }
4721 break;
4722 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004723 case Stmt::ConditionalOperatorClass: {
4724 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4725 if (const Expr *lhs = cond->getLHS())
4726 CheckArrayAccess(lhs);
4727 if (const Expr *rhs = cond->getRHS())
4728 CheckArrayAccess(rhs);
4729 return;
4730 }
4731 default:
4732 return;
4733 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004734 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004735}
John McCallf85e1932011-06-15 23:02:42 +00004736
4737//===--- CHECK: Objective-C retain cycles ----------------------------------//
4738
4739namespace {
4740 struct RetainCycleOwner {
4741 RetainCycleOwner() : Variable(0), Indirect(false) {}
4742 VarDecl *Variable;
4743 SourceRange Range;
4744 SourceLocation Loc;
4745 bool Indirect;
4746
4747 void setLocsFrom(Expr *e) {
4748 Loc = e->getExprLoc();
4749 Range = e->getSourceRange();
4750 }
4751 };
4752}
4753
4754/// Consider whether capturing the given variable can possibly lead to
4755/// a retain cycle.
4756static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4757 // In ARC, it's captured strongly iff the variable has __strong
4758 // lifetime. In MRR, it's captured strongly if the variable is
4759 // __block and has an appropriate type.
4760 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4761 return false;
4762
4763 owner.Variable = var;
4764 owner.setLocsFrom(ref);
4765 return true;
4766}
4767
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004768static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004769 while (true) {
4770 e = e->IgnoreParens();
4771 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4772 switch (cast->getCastKind()) {
4773 case CK_BitCast:
4774 case CK_LValueBitCast:
4775 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004776 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004777 e = cast->getSubExpr();
4778 continue;
4779
John McCallf85e1932011-06-15 23:02:42 +00004780 default:
4781 return false;
4782 }
4783 }
4784
4785 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4786 ObjCIvarDecl *ivar = ref->getDecl();
4787 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4788 return false;
4789
4790 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004791 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004792 return false;
4793
4794 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4795 owner.Indirect = true;
4796 return true;
4797 }
4798
4799 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4800 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4801 if (!var) return false;
4802 return considerVariable(var, ref, owner);
4803 }
4804
John McCallf85e1932011-06-15 23:02:42 +00004805 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4806 if (member->isArrow()) return false;
4807
4808 // Don't count this as an indirect ownership.
4809 e = member->getBase();
4810 continue;
4811 }
4812
John McCall4b9c2d22011-11-06 09:01:30 +00004813 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4814 // Only pay attention to pseudo-objects on property references.
4815 ObjCPropertyRefExpr *pre
4816 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4817 ->IgnoreParens());
4818 if (!pre) return false;
4819 if (pre->isImplicitProperty()) return false;
4820 ObjCPropertyDecl *property = pre->getExplicitProperty();
4821 if (!property->isRetaining() &&
4822 !(property->getPropertyIvarDecl() &&
4823 property->getPropertyIvarDecl()->getType()
4824 .getObjCLifetime() == Qualifiers::OCL_Strong))
4825 return false;
4826
4827 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004828 if (pre->isSuperReceiver()) {
4829 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4830 if (!owner.Variable)
4831 return false;
4832 owner.Loc = pre->getLocation();
4833 owner.Range = pre->getSourceRange();
4834 return true;
4835 }
John McCall4b9c2d22011-11-06 09:01:30 +00004836 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4837 ->getSourceExpr());
4838 continue;
4839 }
4840
John McCallf85e1932011-06-15 23:02:42 +00004841 // Array ivars?
4842
4843 return false;
4844 }
4845}
4846
4847namespace {
4848 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4849 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4850 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4851 Variable(variable), Capturer(0) {}
4852
4853 VarDecl *Variable;
4854 Expr *Capturer;
4855
4856 void VisitDeclRefExpr(DeclRefExpr *ref) {
4857 if (ref->getDecl() == Variable && !Capturer)
4858 Capturer = ref;
4859 }
4860
John McCallf85e1932011-06-15 23:02:42 +00004861 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4862 if (Capturer) return;
4863 Visit(ref->getBase());
4864 if (Capturer && ref->isFreeIvar())
4865 Capturer = ref;
4866 }
4867
4868 void VisitBlockExpr(BlockExpr *block) {
4869 // Look inside nested blocks
4870 if (block->getBlockDecl()->capturesVariable(Variable))
4871 Visit(block->getBlockDecl()->getBody());
4872 }
4873 };
4874}
4875
4876/// Check whether the given argument is a block which captures a
4877/// variable.
4878static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4879 assert(owner.Variable && owner.Loc.isValid());
4880
4881 e = e->IgnoreParenCasts();
4882 BlockExpr *block = dyn_cast<BlockExpr>(e);
4883 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4884 return 0;
4885
4886 FindCaptureVisitor visitor(S.Context, owner.Variable);
4887 visitor.Visit(block->getBlockDecl()->getBody());
4888 return visitor.Capturer;
4889}
4890
4891static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4892 RetainCycleOwner &owner) {
4893 assert(capturer);
4894 assert(owner.Variable && owner.Loc.isValid());
4895
4896 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4897 << owner.Variable << capturer->getSourceRange();
4898 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4899 << owner.Indirect << owner.Range;
4900}
4901
4902/// Check for a keyword selector that starts with the word 'add' or
4903/// 'set'.
4904static bool isSetterLikeSelector(Selector sel) {
4905 if (sel.isUnarySelector()) return false;
4906
Chris Lattner5f9e2722011-07-23 10:55:15 +00004907 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004908 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004909 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004910 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004911 else if (str.startswith("add")) {
4912 // Specially whitelist 'addOperationWithBlock:'.
4913 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4914 return false;
4915 str = str.substr(3);
4916 }
John McCallf85e1932011-06-15 23:02:42 +00004917 else
4918 return false;
4919
4920 if (str.empty()) return true;
4921 return !islower(str.front());
4922}
4923
4924/// Check a message send to see if it's likely to cause a retain cycle.
4925void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4926 // Only check instance methods whose selector looks like a setter.
4927 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4928 return;
4929
4930 // Try to find a variable that the receiver is strongly owned by.
4931 RetainCycleOwner owner;
4932 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004933 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004934 return;
4935 } else {
4936 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4937 owner.Variable = getCurMethodDecl()->getSelfDecl();
4938 owner.Loc = msg->getSuperLoc();
4939 owner.Range = msg->getSuperLoc();
4940 }
4941
4942 // Check whether the receiver is captured by any of the arguments.
4943 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4944 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4945 return diagnoseRetainCycle(*this, capturer, owner);
4946}
4947
4948/// Check a property assign to see if it's likely to cause a retain cycle.
4949void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4950 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004951 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004952 return;
4953
4954 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4955 diagnoseRetainCycle(*this, capturer, owner);
4956}
4957
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004958bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004959 QualType LHS, Expr *RHS) {
4960 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4961 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004962 return false;
4963 // strip off any implicit cast added to get to the one arc-specific
4964 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004965 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004966 Diag(Loc, diag::warn_arc_retained_assign)
4967 << (LT == Qualifiers::OCL_ExplicitNone)
4968 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004969 return true;
4970 }
4971 RHS = cast->getSubExpr();
4972 }
4973 return false;
John McCallf85e1932011-06-15 23:02:42 +00004974}
4975
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004976void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4977 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004978 QualType LHSType;
4979 // PropertyRef on LHS type need be directly obtained from
4980 // its declaration as it has a PsuedoType.
4981 ObjCPropertyRefExpr *PRE
4982 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4983 if (PRE && !PRE->isImplicitProperty()) {
4984 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4985 if (PD)
4986 LHSType = PD->getType();
4987 }
4988
4989 if (LHSType.isNull())
4990 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004991 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4992 return;
4993 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4994 // FIXME. Check for other life times.
4995 if (LT != Qualifiers::OCL_None)
4996 return;
4997
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004998 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004999 if (PRE->isImplicitProperty())
5000 return;
5001 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5002 if (!PD)
5003 return;
5004
5005 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005006 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5007 // when 'assign' attribute was not explicitly specified
5008 // by user, ignore it and rely on property type itself
5009 // for lifetime info.
5010 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5011 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5012 LHSType->isObjCRetainableType())
5013 return;
5014
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005015 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005016 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005017 Diag(Loc, diag::warn_arc_retained_property_assign)
5018 << RHS->getSourceRange();
5019 return;
5020 }
5021 RHS = cast->getSubExpr();
5022 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005023 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005024 }
5025}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005026
5027//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5028
5029namespace {
5030bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5031 SourceLocation StmtLoc,
5032 const NullStmt *Body) {
5033 // Do not warn if the body is a macro that expands to nothing, e.g:
5034 //
5035 // #define CALL(x)
5036 // if (condition)
5037 // CALL(0);
5038 //
5039 if (Body->hasLeadingEmptyMacro())
5040 return false;
5041
5042 // Get line numbers of statement and body.
5043 bool StmtLineInvalid;
5044 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5045 &StmtLineInvalid);
5046 if (StmtLineInvalid)
5047 return false;
5048
5049 bool BodyLineInvalid;
5050 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5051 &BodyLineInvalid);
5052 if (BodyLineInvalid)
5053 return false;
5054
5055 // Warn if null statement and body are on the same line.
5056 if (StmtLine != BodyLine)
5057 return false;
5058
5059 return true;
5060}
5061} // Unnamed namespace
5062
5063void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5064 const Stmt *Body,
5065 unsigned DiagID) {
5066 // Since this is a syntactic check, don't emit diagnostic for template
5067 // instantiations, this just adds noise.
5068 if (CurrentInstantiationScope)
5069 return;
5070
5071 // The body should be a null statement.
5072 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5073 if (!NBody)
5074 return;
5075
5076 // Do the usual checks.
5077 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5078 return;
5079
5080 Diag(NBody->getSemiLoc(), DiagID);
5081 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5082}
5083
5084void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5085 const Stmt *PossibleBody) {
5086 assert(!CurrentInstantiationScope); // Ensured by caller
5087
5088 SourceLocation StmtLoc;
5089 const Stmt *Body;
5090 unsigned DiagID;
5091 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5092 StmtLoc = FS->getRParenLoc();
5093 Body = FS->getBody();
5094 DiagID = diag::warn_empty_for_body;
5095 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5096 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5097 Body = WS->getBody();
5098 DiagID = diag::warn_empty_while_body;
5099 } else
5100 return; // Neither `for' nor `while'.
5101
5102 // The body should be a null statement.
5103 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5104 if (!NBody)
5105 return;
5106
5107 // Skip expensive checks if diagnostic is disabled.
5108 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5109 DiagnosticsEngine::Ignored)
5110 return;
5111
5112 // Do the usual checks.
5113 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5114 return;
5115
5116 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5117 // noise level low, emit diagnostics only if for/while is followed by a
5118 // CompoundStmt, e.g.:
5119 // for (int i = 0; i < n; i++);
5120 // {
5121 // a(i);
5122 // }
5123 // or if for/while is followed by a statement with more indentation
5124 // than for/while itself:
5125 // for (int i = 0; i < n; i++);
5126 // a(i);
5127 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5128 if (!ProbableTypo) {
5129 bool BodyColInvalid;
5130 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5131 PossibleBody->getLocStart(),
5132 &BodyColInvalid);
5133 if (BodyColInvalid)
5134 return;
5135
5136 bool StmtColInvalid;
5137 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5138 S->getLocStart(),
5139 &StmtColInvalid);
5140 if (StmtColInvalid)
5141 return;
5142
5143 if (BodyCol > StmtCol)
5144 ProbableTypo = true;
5145 }
5146
5147 if (ProbableTypo) {
5148 Diag(NBody->getSemiLoc(), DiagID);
5149 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5150 }
5151}