blob: 0e2eb3c701716155584f6f02ebe843297a751a24 [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));
Eli Friedman276b0612011-10-11 02:20:01 +0000253 case Builtin::BI__atomic_load:
254 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
255 case Builtin::BI__atomic_store:
256 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000257 case Builtin::BI__atomic_init:
258 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000259 case Builtin::BI__atomic_exchange:
260 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
261 case Builtin::BI__atomic_compare_exchange_strong:
262 return SemaAtomicOpsOverloaded(move(TheCallResult),
263 AtomicExpr::CmpXchgStrong);
264 case Builtin::BI__atomic_compare_exchange_weak:
265 return SemaAtomicOpsOverloaded(move(TheCallResult),
266 AtomicExpr::CmpXchgWeak);
267 case Builtin::BI__atomic_fetch_add:
268 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
269 case Builtin::BI__atomic_fetch_sub:
270 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
271 case Builtin::BI__atomic_fetch_and:
272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
273 case Builtin::BI__atomic_fetch_or:
274 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
275 case Builtin::BI__atomic_fetch_xor:
276 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 case Builtin::BI__builtin_annotation:
278 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
279 return ExprError();
280 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000281 }
282
283 // Since the target specific builtins for each arch overlap, only check those
284 // of the arch we are compiling for.
285 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000286 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000287 case llvm::Triple::arm:
288 case llvm::Triple::thumb:
289 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
290 return ExprError();
291 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000292 default:
293 break;
294 }
295 }
296
297 return move(TheCallResult);
298}
299
Nate Begeman61eecf52010-06-14 05:21:25 +0000300// Get the valid immediate range for the specified NEON type code.
301static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000302 NeonTypeFlags Type(t);
303 int IsQuad = Type.isQuad();
304 switch (Type.getEltType()) {
305 case NeonTypeFlags::Int8:
306 case NeonTypeFlags::Poly8:
307 return shift ? 7 : (8 << IsQuad) - 1;
308 case NeonTypeFlags::Int16:
309 case NeonTypeFlags::Poly16:
310 return shift ? 15 : (4 << IsQuad) - 1;
311 case NeonTypeFlags::Int32:
312 return shift ? 31 : (2 << IsQuad) - 1;
313 case NeonTypeFlags::Int64:
314 return shift ? 63 : (1 << IsQuad) - 1;
315 case NeonTypeFlags::Float16:
316 assert(!shift && "cannot shift float types!");
317 return (4 << IsQuad) - 1;
318 case NeonTypeFlags::Float32:
319 assert(!shift && "cannot shift float types!");
320 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000321 }
David Blaikie7530c032012-01-17 06:56:22 +0000322 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000323}
324
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000325/// getNeonEltType - Return the QualType corresponding to the elements of
326/// the vector type specified by the NeonTypeFlags. This is used to check
327/// the pointer arguments for Neon load/store intrinsics.
328static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
329 switch (Flags.getEltType()) {
330 case NeonTypeFlags::Int8:
331 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
332 case NeonTypeFlags::Int16:
333 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
334 case NeonTypeFlags::Int32:
335 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
336 case NeonTypeFlags::Int64:
337 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
338 case NeonTypeFlags::Poly8:
339 return Context.SignedCharTy;
340 case NeonTypeFlags::Poly16:
341 return Context.ShortTy;
342 case NeonTypeFlags::Float16:
343 return Context.UnsignedShortTy;
344 case NeonTypeFlags::Float32:
345 return Context.FloatTy;
346 }
David Blaikie7530c032012-01-17 06:56:22 +0000347 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000348}
349
Nate Begeman26a31422010-06-08 02:47:44 +0000350bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000351 llvm::APSInt Result;
352
Nate Begeman0d15c532010-06-13 04:47:52 +0000353 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000354 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000355 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000357 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000358#define GET_NEON_OVERLOAD_CHECK
359#include "clang/Basic/arm_neon.inc"
360#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000361 }
362
Nate Begeman0d15c532010-06-13 04:47:52 +0000363 // For NEON intrinsics which are overloaded on vector element type, validate
364 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000365 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000366 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000367 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 return true;
369
Bob Wilsonda95f732011-11-08 01:16:11 +0000370 TV = Result.getLimitedValue(64);
371 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000372 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000373 << TheCall->getArg(ImmArg)->getSourceRange();
374 }
375
Bob Wilson46482552011-11-16 21:32:23 +0000376 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000378 Expr *Arg = TheCall->getArg(PtrArgNum);
379 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
380 Arg = ICE->getSubExpr();
381 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
382 QualType RHSTy = RHS.get()->getType();
383 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
384 if (HasConstPtr)
385 EltTy = EltTy.withConst();
386 QualType LHSTy = Context.getPointerType(EltTy);
387 AssignConvertType ConvTy;
388 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
389 if (RHS.isInvalid())
390 return true;
391 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
392 RHS.get(), AA_Assigning))
393 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000394 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000395
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 // For NEON intrinsics which take an immediate value as part of the
397 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000398 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 switch (BuiltinID) {
400 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000401 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
402 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000403 case ARM::BI__builtin_arm_vcvtr_f:
404 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000405#define GET_NEON_IMMEDIATE_CHECK
406#include "clang/Basic/arm_neon.inc"
407#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000408 };
409
Nate Begeman61eecf52010-06-14 05:21:25 +0000410 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000411 if (SemaBuiltinConstantArg(TheCall, i, Result))
412 return true;
413
Nate Begeman61eecf52010-06-14 05:21:25 +0000414 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000415 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000416 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000417 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000418 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000419
Nate Begeman99c40bb2010-08-03 21:32:34 +0000420 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000421 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000422}
Daniel Dunbarde454282008-10-02 18:44:07 +0000423
Anders Carlssond406bf02009-08-16 01:56:34 +0000424/// CheckFunctionCall - Check a direct function call for various correctness
425/// and safety properties not strictly enforced by the C type system.
426bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
427 // Get the IdentifierInfo* for the called function.
428 IdentifierInfo *FnInfo = FDecl->getIdentifier();
429
430 // None of the checks below are needed for functions that don't have
431 // simple names (e.g., C++ conversion functions).
432 if (!FnInfo)
433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Daniel Dunbarde454282008-10-02 18:44:07 +0000435 // FIXME: This mechanism should be abstracted to be less fragile and
436 // more efficient. For example, just map function ids to custom
437 // handlers.
438
Ted Kremenekc82faca2010-09-09 04:33:05 +0000439 // Printf and scanf checking.
440 for (specific_attr_iterator<FormatAttr>
441 i = FDecl->specific_attr_begin<FormatAttr>(),
442 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000443 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Ted Kremenekc82faca2010-09-09 04:33:05 +0000446 for (specific_attr_iterator<NonNullAttr>
447 i = FDecl->specific_attr_begin<NonNullAttr>(),
448 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000449 CheckNonNullArguments(*i, TheCall->getArgs(),
450 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000451 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000452
Anna Zaks0a151a12012-01-17 00:37:07 +0000453 unsigned CMId = FDecl->getMemoryFunctionKind();
454 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000455 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000456
Anna Zaksd9b859a2012-01-13 21:52:01 +0000457 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000458 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000459 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000460 else if (CMId == Builtin::BIstrncat)
461 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000462 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000463 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000464
Anders Carlssond406bf02009-08-16 01:56:34 +0000465 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000466}
467
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000468bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
469 Expr **Args, unsigned NumArgs) {
470 for (specific_attr_iterator<FormatAttr>
471 i = Method->specific_attr_begin<FormatAttr>(),
472 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
473
474 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
475 Method->getSourceRange());
476 }
477
478 // diagnose nonnull arguments.
479 for (specific_attr_iterator<NonNullAttr>
480 i = Method->specific_attr_begin<NonNullAttr>(),
481 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
482 CheckNonNullArguments(*i, Args, lbrac);
483 }
484
485 return false;
486}
487
Anders Carlssond406bf02009-08-16 01:56:34 +0000488bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000489 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
490 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000493 QualType Ty = V->getType();
494 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000495 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000497 // format string checking.
498 for (specific_attr_iterator<FormatAttr>
499 i = NDecl->specific_attr_begin<FormatAttr>(),
500 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
501 CheckFormatArguments(*i, TheCall);
502 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000503
504 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000505}
506
Eli Friedman276b0612011-10-11 02:20:01 +0000507ExprResult
508Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
509 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
510 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000511
512 // All these operations take one of the following four forms:
513 // T __atomic_load(_Atomic(T)*, int) (loads)
514 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
515 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
516 // (cmpxchg)
517 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
518 // where T is an appropriate type, and the int paremeterss are for orderings.
519 unsigned NumVals = 1;
520 unsigned NumOrders = 1;
521 if (Op == AtomicExpr::Load) {
522 NumVals = 0;
523 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
524 NumVals = 2;
525 NumOrders = 2;
526 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000527 if (Op == AtomicExpr::Init)
528 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000529
530 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
532 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
533 << TheCall->getCallee()->getSourceRange();
534 return ExprError();
535 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
536 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
537 diag::err_typecheck_call_too_many_args)
538 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
539 << TheCall->getCallee()->getSourceRange();
540 return ExprError();
541 }
542
543 // Inspect the first argument of the atomic operation. This should always be
544 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000545 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000546 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
547 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
548 if (!pointerType) {
549 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
550 << Ptr->getType() << Ptr->getSourceRange();
551 return ExprError();
552 }
553
554 QualType AtomTy = pointerType->getPointeeType();
555 if (!AtomTy->isAtomicType()) {
556 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
557 << Ptr->getType() << Ptr->getSourceRange();
558 return ExprError();
559 }
560 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
561
562 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
563 !ValType->isIntegerType() && !ValType->isPointerType()) {
564 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
565 << Ptr->getType() << Ptr->getSourceRange();
566 return ExprError();
567 }
568
569 if (!ValType->isIntegerType() &&
570 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
571 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
572 << Ptr->getType() << Ptr->getSourceRange();
573 return ExprError();
574 }
575
576 switch (ValType.getObjCLifetime()) {
577 case Qualifiers::OCL_None:
578 case Qualifiers::OCL_ExplicitNone:
579 // okay
580 break;
581
582 case Qualifiers::OCL_Weak:
583 case Qualifiers::OCL_Strong:
584 case Qualifiers::OCL_Autoreleasing:
585 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
586 << ValType << Ptr->getSourceRange();
587 return ExprError();
588 }
589
590 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000591 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000592 ResultType = Context.VoidTy;
593 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
594 ResultType = Context.BoolTy;
595
596 // The first argument --- the pointer --- has a fixed type; we
597 // deduce the types of the rest of the arguments accordingly. Walk
598 // the remaining arguments, converting them to the deduced value type.
599 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
600 ExprResult Arg = TheCall->getArg(i);
601 QualType Ty;
602 if (i < NumVals+1) {
603 // The second argument to a cmpxchg is a pointer to the data which will
604 // be exchanged. The second argument to a pointer add/subtract is the
605 // amount to add/subtract, which must be a ptrdiff_t. The third
606 // argument to a cmpxchg and the second argument in all other cases
607 // is the type of the value.
608 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
609 Op == AtomicExpr::CmpXchgStrong))
610 Ty = Context.getPointerType(ValType.getUnqualifiedType());
611 else if (!ValType->isIntegerType() &&
612 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
613 Ty = Context.getPointerDiffType();
614 else
615 Ty = ValType;
616 } else {
617 // The order(s) are always converted to int.
618 Ty = Context.IntTy;
619 }
620 InitializedEntity Entity =
621 InitializedEntity::InitializeParameter(Context, Ty, false);
622 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
623 if (Arg.isInvalid())
624 return true;
625 TheCall->setArg(i, Arg.get());
626 }
627
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000628 SmallVector<Expr*, 5> SubExprs;
629 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000630 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000631 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000632 } else if (Op == AtomicExpr::Init) {
633 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000634 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000635 SubExprs.push_back(TheCall->getArg(2)); // Order
636 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000637 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000638 SubExprs.push_back(TheCall->getArg(3)); // Order
639 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000640 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000641 SubExprs.push_back(TheCall->getArg(2)); // Val2
Eli Friedman276b0612011-10-11 02:20:01 +0000642 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000643
644 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
645 SubExprs.data(), SubExprs.size(),
646 ResultType, Op,
647 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000648}
649
650
John McCall5f8d6042011-08-27 01:09:30 +0000651/// checkBuiltinArgument - Given a call to a builtin function, perform
652/// normal type-checking on the given argument, updating the call in
653/// place. This is useful when a builtin function requires custom
654/// type-checking for some of its arguments but not necessarily all of
655/// them.
656///
657/// Returns true on error.
658static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
659 FunctionDecl *Fn = E->getDirectCallee();
660 assert(Fn && "builtin call without direct callee!");
661
662 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
663 InitializedEntity Entity =
664 InitializedEntity::InitializeParameter(S.Context, Param);
665
666 ExprResult Arg = E->getArg(0);
667 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
668 if (Arg.isInvalid())
669 return true;
670
671 E->setArg(ArgIndex, Arg.take());
672 return false;
673}
674
Chris Lattner5caa3702009-05-08 06:58:22 +0000675/// SemaBuiltinAtomicOverloaded - We have a call to a function like
676/// __sync_fetch_and_add, which is an overloaded function based on the pointer
677/// type of its first argument. The main ActOnCallExpr routines have already
678/// promoted the types of arguments because all of these calls are prototyped as
679/// void(...).
680///
681/// This function goes through and does final semantic checking for these
682/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000683ExprResult
684Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000685 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000686 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
687 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
688
689 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000690 if (TheCall->getNumArgs() < 1) {
691 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
692 << 0 << 1 << TheCall->getNumArgs()
693 << TheCall->getCallee()->getSourceRange();
694 return ExprError();
695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner5caa3702009-05-08 06:58:22 +0000697 // Inspect the first argument of the atomic builtin. This should always be
698 // a pointer type, whose element is an integral scalar or pointer type.
699 // Because it is a pointer type, we don't have to worry about any implicit
700 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000701 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000703 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
704 if (FirstArgResult.isInvalid())
705 return ExprError();
706 FirstArg = FirstArgResult.take();
707 TheCall->setArg(0, FirstArg);
708
John McCallf85e1932011-06-15 23:02:42 +0000709 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
710 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000711 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
712 << FirstArg->getType() << FirstArg->getSourceRange();
713 return ExprError();
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
John McCallf85e1932011-06-15 23:02:42 +0000716 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000717 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000718 !ValType->isBlockPointerType()) {
719 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
720 << FirstArg->getType() << FirstArg->getSourceRange();
721 return ExprError();
722 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000723
John McCallf85e1932011-06-15 23:02:42 +0000724 switch (ValType.getObjCLifetime()) {
725 case Qualifiers::OCL_None:
726 case Qualifiers::OCL_ExplicitNone:
727 // okay
728 break;
729
730 case Qualifiers::OCL_Weak:
731 case Qualifiers::OCL_Strong:
732 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000733 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000734 << ValType << FirstArg->getSourceRange();
735 return ExprError();
736 }
737
John McCallb45ae252011-10-05 07:41:44 +0000738 // Strip any qualifiers off ValType.
739 ValType = ValType.getUnqualifiedType();
740
Chandler Carruth8d13d222010-07-18 20:54:12 +0000741 // The majority of builtins return a value, but a few have special return
742 // types, so allow them to override appropriately below.
743 QualType ResultType = ValType;
744
Chris Lattner5caa3702009-05-08 06:58:22 +0000745 // We need to figure out which concrete builtin this maps onto. For example,
746 // __sync_fetch_and_add with a 2 byte object turns into
747 // __sync_fetch_and_add_2.
748#define BUILTIN_ROW(x) \
749 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
750 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattner5caa3702009-05-08 06:58:22 +0000752 static const unsigned BuiltinIndices[][5] = {
753 BUILTIN_ROW(__sync_fetch_and_add),
754 BUILTIN_ROW(__sync_fetch_and_sub),
755 BUILTIN_ROW(__sync_fetch_and_or),
756 BUILTIN_ROW(__sync_fetch_and_and),
757 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattner5caa3702009-05-08 06:58:22 +0000759 BUILTIN_ROW(__sync_add_and_fetch),
760 BUILTIN_ROW(__sync_sub_and_fetch),
761 BUILTIN_ROW(__sync_and_and_fetch),
762 BUILTIN_ROW(__sync_or_and_fetch),
763 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5caa3702009-05-08 06:58:22 +0000765 BUILTIN_ROW(__sync_val_compare_and_swap),
766 BUILTIN_ROW(__sync_bool_compare_and_swap),
767 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000768 BUILTIN_ROW(__sync_lock_release),
769 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000770 };
Mike Stump1eb44332009-09-09 15:08:12 +0000771#undef BUILTIN_ROW
772
Chris Lattner5caa3702009-05-08 06:58:22 +0000773 // Determine the index of the size.
774 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000775 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 case 1: SizeIndex = 0; break;
777 case 2: SizeIndex = 1; break;
778 case 4: SizeIndex = 2; break;
779 case 8: SizeIndex = 3; break;
780 case 16: SizeIndex = 4; break;
781 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000782 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
783 << FirstArg->getType() << FirstArg->getSourceRange();
784 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 // Each of these builtins has one pointer argument, followed by some number of
788 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
789 // that we ignore. Find out which row of BuiltinIndices to read from as well
790 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000791 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000792 unsigned BuiltinIndex, NumFixed = 1;
793 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000794 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000795 case Builtin::BI__sync_fetch_and_add:
796 case Builtin::BI__sync_fetch_and_add_1:
797 case Builtin::BI__sync_fetch_and_add_2:
798 case Builtin::BI__sync_fetch_and_add_4:
799 case Builtin::BI__sync_fetch_and_add_8:
800 case Builtin::BI__sync_fetch_and_add_16:
801 BuiltinIndex = 0;
802 break;
803
804 case Builtin::BI__sync_fetch_and_sub:
805 case Builtin::BI__sync_fetch_and_sub_1:
806 case Builtin::BI__sync_fetch_and_sub_2:
807 case Builtin::BI__sync_fetch_and_sub_4:
808 case Builtin::BI__sync_fetch_and_sub_8:
809 case Builtin::BI__sync_fetch_and_sub_16:
810 BuiltinIndex = 1;
811 break;
812
813 case Builtin::BI__sync_fetch_and_or:
814 case Builtin::BI__sync_fetch_and_or_1:
815 case Builtin::BI__sync_fetch_and_or_2:
816 case Builtin::BI__sync_fetch_and_or_4:
817 case Builtin::BI__sync_fetch_and_or_8:
818 case Builtin::BI__sync_fetch_and_or_16:
819 BuiltinIndex = 2;
820 break;
821
822 case Builtin::BI__sync_fetch_and_and:
823 case Builtin::BI__sync_fetch_and_and_1:
824 case Builtin::BI__sync_fetch_and_and_2:
825 case Builtin::BI__sync_fetch_and_and_4:
826 case Builtin::BI__sync_fetch_and_and_8:
827 case Builtin::BI__sync_fetch_and_and_16:
828 BuiltinIndex = 3;
829 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Douglas Gregora9766412011-11-28 16:30:08 +0000831 case Builtin::BI__sync_fetch_and_xor:
832 case Builtin::BI__sync_fetch_and_xor_1:
833 case Builtin::BI__sync_fetch_and_xor_2:
834 case Builtin::BI__sync_fetch_and_xor_4:
835 case Builtin::BI__sync_fetch_and_xor_8:
836 case Builtin::BI__sync_fetch_and_xor_16:
837 BuiltinIndex = 4;
838 break;
839
840 case Builtin::BI__sync_add_and_fetch:
841 case Builtin::BI__sync_add_and_fetch_1:
842 case Builtin::BI__sync_add_and_fetch_2:
843 case Builtin::BI__sync_add_and_fetch_4:
844 case Builtin::BI__sync_add_and_fetch_8:
845 case Builtin::BI__sync_add_and_fetch_16:
846 BuiltinIndex = 5;
847 break;
848
849 case Builtin::BI__sync_sub_and_fetch:
850 case Builtin::BI__sync_sub_and_fetch_1:
851 case Builtin::BI__sync_sub_and_fetch_2:
852 case Builtin::BI__sync_sub_and_fetch_4:
853 case Builtin::BI__sync_sub_and_fetch_8:
854 case Builtin::BI__sync_sub_and_fetch_16:
855 BuiltinIndex = 6;
856 break;
857
858 case Builtin::BI__sync_and_and_fetch:
859 case Builtin::BI__sync_and_and_fetch_1:
860 case Builtin::BI__sync_and_and_fetch_2:
861 case Builtin::BI__sync_and_and_fetch_4:
862 case Builtin::BI__sync_and_and_fetch_8:
863 case Builtin::BI__sync_and_and_fetch_16:
864 BuiltinIndex = 7;
865 break;
866
867 case Builtin::BI__sync_or_and_fetch:
868 case Builtin::BI__sync_or_and_fetch_1:
869 case Builtin::BI__sync_or_and_fetch_2:
870 case Builtin::BI__sync_or_and_fetch_4:
871 case Builtin::BI__sync_or_and_fetch_8:
872 case Builtin::BI__sync_or_and_fetch_16:
873 BuiltinIndex = 8;
874 break;
875
876 case Builtin::BI__sync_xor_and_fetch:
877 case Builtin::BI__sync_xor_and_fetch_1:
878 case Builtin::BI__sync_xor_and_fetch_2:
879 case Builtin::BI__sync_xor_and_fetch_4:
880 case Builtin::BI__sync_xor_and_fetch_8:
881 case Builtin::BI__sync_xor_and_fetch_16:
882 BuiltinIndex = 9;
883 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner5caa3702009-05-08 06:58:22 +0000885 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000886 case Builtin::BI__sync_val_compare_and_swap_1:
887 case Builtin::BI__sync_val_compare_and_swap_2:
888 case Builtin::BI__sync_val_compare_and_swap_4:
889 case Builtin::BI__sync_val_compare_and_swap_8:
890 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000891 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000892 NumFixed = 2;
893 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000896 case Builtin::BI__sync_bool_compare_and_swap_1:
897 case Builtin::BI__sync_bool_compare_and_swap_2:
898 case Builtin::BI__sync_bool_compare_and_swap_4:
899 case Builtin::BI__sync_bool_compare_and_swap_8:
900 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000901 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000903 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000904 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000905
906 case Builtin::BI__sync_lock_test_and_set:
907 case Builtin::BI__sync_lock_test_and_set_1:
908 case Builtin::BI__sync_lock_test_and_set_2:
909 case Builtin::BI__sync_lock_test_and_set_4:
910 case Builtin::BI__sync_lock_test_and_set_8:
911 case Builtin::BI__sync_lock_test_and_set_16:
912 BuiltinIndex = 12;
913 break;
914
Chris Lattner5caa3702009-05-08 06:58:22 +0000915 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000916 case Builtin::BI__sync_lock_release_1:
917 case Builtin::BI__sync_lock_release_2:
918 case Builtin::BI__sync_lock_release_4:
919 case Builtin::BI__sync_lock_release_8:
920 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000921 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000922 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000923 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000924 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000925
926 case Builtin::BI__sync_swap:
927 case Builtin::BI__sync_swap_1:
928 case Builtin::BI__sync_swap_2:
929 case Builtin::BI__sync_swap_4:
930 case Builtin::BI__sync_swap_8:
931 case Builtin::BI__sync_swap_16:
932 BuiltinIndex = 14;
933 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner5caa3702009-05-08 06:58:22 +0000936 // Now that we know how many fixed arguments we expect, first check that we
937 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000938 if (TheCall->getNumArgs() < 1+NumFixed) {
939 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
940 << 0 << 1+NumFixed << TheCall->getNumArgs()
941 << TheCall->getCallee()->getSourceRange();
942 return ExprError();
943 }
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000945 // Get the decl for the concrete builtin from this, we can tell what the
946 // concrete integer type we should convert to is.
947 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
948 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
949 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000950 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000951 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
952 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000953
John McCallf871d0c2010-08-07 06:22:56 +0000954 // The first argument --- the pointer --- has a fixed type; we
955 // deduce the types of the rest of the arguments accordingly. Walk
956 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000957 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000958 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner5caa3702009-05-08 06:58:22 +0000960 // GCC does an implicit conversion to the pointer or integer ValType. This
961 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000962 // Initialize the argument.
963 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
964 ValType, /*consume*/ false);
965 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000966 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000967 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner5caa3702009-05-08 06:58:22 +0000969 // Okay, we have something that *can* be converted to the right type. Check
970 // to see if there is a potentially weird extension going on here. This can
971 // happen when you do an atomic operation on something like an char* and
972 // pass in 42. The 42 gets converted to char. This is even more strange
973 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000974 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000975 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000978 ASTContext& Context = this->getASTContext();
979
980 // Create a new DeclRefExpr to refer to the new decl.
981 DeclRefExpr* NewDRE = DeclRefExpr::Create(
982 Context,
983 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000984 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000985 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +0000986 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000987 DRE->getLocation(),
988 NewBuiltinDecl->getType(),
989 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner5caa3702009-05-08 06:58:22 +0000991 // Set the callee in the CallExpr.
992 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000993 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000994 if (PromotedCall.isInvalid())
995 return ExprError();
996 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000998 // Change the result type of the call to match the original value type. This
999 // is arbitrary, but the codegen for these builtins ins design to handle it
1000 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001001 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001002
1003 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001004}
1005
Chris Lattner69039812009-02-18 06:01:06 +00001006/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001007/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001008/// Note: It might also make sense to do the UTF-16 conversion here (would
1009/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001010bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001011 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001012 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1013
Douglas Gregor5cee1192011-07-27 05:40:30 +00001014 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001015 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1016 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001017 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001020 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001021 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001022 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001023 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001024 const UTF8 *FromPtr = (UTF8 *)String.data();
1025 UTF16 *ToPtr = &ToBuf[0];
1026
1027 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1028 &ToPtr, ToPtr + NumBytes,
1029 strictConversion);
1030 // Check for conversion failure.
1031 if (Result != conversionOK)
1032 Diag(Arg->getLocStart(),
1033 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1034 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001035 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001036}
1037
Chris Lattnerc27c6652007-12-20 00:05:45 +00001038/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1039/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001040bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1041 Expr *Fn = TheCall->getCallee();
1042 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001043 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001044 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001045 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1046 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001047 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001048 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001049 return true;
1050 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001051
1052 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001053 return Diag(TheCall->getLocEnd(),
1054 diag::err_typecheck_call_too_few_args_at_least)
1055 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001056 }
1057
John McCall5f8d6042011-08-27 01:09:30 +00001058 // Type-check the first argument normally.
1059 if (checkBuiltinArgument(*this, TheCall, 0))
1060 return true;
1061
Chris Lattnerc27c6652007-12-20 00:05:45 +00001062 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001063 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001064 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001065 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001066 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001067 else if (FunctionDecl *FD = getCurFunctionDecl())
1068 isVariadic = FD->isVariadic();
1069 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001070 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattnerc27c6652007-12-20 00:05:45 +00001072 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001073 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1074 return true;
1075 }
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Chris Lattner30ce3442007-12-19 23:59:04 +00001077 // Verify that the second argument to the builtin is the last argument of the
1078 // current function or method.
1079 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001080 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Anders Carlsson88cf2262008-02-11 04:20:54 +00001082 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1083 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001084 // FIXME: This isn't correct for methods (results in bogus warning).
1085 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001086 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001087 if (CurBlock)
1088 LastArg = *(CurBlock->TheDecl->param_end()-1);
1089 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001090 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001091 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001092 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001093 SecondArgIsLastNamedArgument = PV == LastArg;
1094 }
1095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Chris Lattner30ce3442007-12-19 23:59:04 +00001097 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001098 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001099 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1100 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001101}
Chris Lattner30ce3442007-12-19 23:59:04 +00001102
Chris Lattner1b9a0792007-12-20 00:26:33 +00001103/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1104/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001105bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1106 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001107 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001108 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001109 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001110 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001111 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001112 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001113 << SourceRange(TheCall->getArg(2)->getLocStart(),
1114 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001115
John Wiegley429bb272011-04-08 18:41:53 +00001116 ExprResult OrigArg0 = TheCall->getArg(0);
1117 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001118
Chris Lattner1b9a0792007-12-20 00:26:33 +00001119 // Do standard promotions between the two arguments, returning their common
1120 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001121 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001122 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1123 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001124
1125 // Make sure any conversions are pushed back into the call; this is
1126 // type safe since unordered compare builtins are declared as "_Bool
1127 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001128 TheCall->setArg(0, OrigArg0.get());
1129 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001130
John Wiegley429bb272011-04-08 18:41:53 +00001131 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001132 return false;
1133
Chris Lattner1b9a0792007-12-20 00:26:33 +00001134 // If the common type isn't a real floating type, then the arguments were
1135 // invalid for this operation.
1136 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001137 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001138 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001139 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1140 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Chris Lattner1b9a0792007-12-20 00:26:33 +00001142 return false;
1143}
1144
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001145/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1146/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001147/// to check everything. We expect the last argument to be a floating point
1148/// value.
1149bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1150 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001151 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001152 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001153 if (TheCall->getNumArgs() > NumArgs)
1154 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001155 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001156 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001157 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001158 (*(TheCall->arg_end()-1))->getLocEnd());
1159
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001160 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Eli Friedman9ac6f622009-08-31 20:06:00 +00001162 if (OrigArg->isTypeDependent())
1163 return false;
1164
Chris Lattner81368fb2010-05-06 05:50:07 +00001165 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001166 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001167 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001168 diag::err_typecheck_call_invalid_unary_fp)
1169 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattner81368fb2010-05-06 05:50:07 +00001171 // If this is an implicit conversion from float -> double, remove it.
1172 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1173 Expr *CastArg = Cast->getSubExpr();
1174 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1175 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1176 "promotion from float to double is the only expected cast here");
1177 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001178 TheCall->setArg(NumArgs-1, CastArg);
1179 OrigArg = CastArg;
1180 }
1181 }
1182
Eli Friedman9ac6f622009-08-31 20:06:00 +00001183 return false;
1184}
1185
Eli Friedmand38617c2008-05-14 19:38:39 +00001186/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1187// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001188ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001189 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001190 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001191 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001192 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001193 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001194
Nate Begeman37b6a572010-06-08 00:16:34 +00001195 // Determine which of the following types of shufflevector we're checking:
1196 // 1) unary, vector mask: (lhs, mask)
1197 // 2) binary, vector mask: (lhs, rhs, mask)
1198 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1199 QualType resType = TheCall->getArg(0)->getType();
1200 unsigned numElements = 0;
1201
Douglas Gregorcde01732009-05-19 22:10:17 +00001202 if (!TheCall->getArg(0)->isTypeDependent() &&
1203 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001204 QualType LHSType = TheCall->getArg(0)->getType();
1205 QualType RHSType = TheCall->getArg(1)->getType();
1206
1207 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001208 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001209 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001210 TheCall->getArg(1)->getLocEnd());
1211 return ExprError();
1212 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001213
1214 numElements = LHSType->getAs<VectorType>()->getNumElements();
1215 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Nate Begeman37b6a572010-06-08 00:16:34 +00001217 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1218 // with mask. If so, verify that RHS is an integer vector type with the
1219 // same number of elts as lhs.
1220 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001221 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001222 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1223 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1224 << SourceRange(TheCall->getArg(1)->getLocStart(),
1225 TheCall->getArg(1)->getLocEnd());
1226 numResElements = numElements;
1227 }
1228 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001229 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001230 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001231 TheCall->getArg(1)->getLocEnd());
1232 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001233 } else if (numElements != numResElements) {
1234 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001235 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001236 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001237 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001238 }
1239
1240 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001241 if (TheCall->getArg(i)->isTypeDependent() ||
1242 TheCall->getArg(i)->isValueDependent())
1243 continue;
1244
Nate Begeman37b6a572010-06-08 00:16:34 +00001245 llvm::APSInt Result(32);
1246 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1247 return ExprError(Diag(TheCall->getLocStart(),
1248 diag::err_shufflevector_nonconstant_argument)
1249 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001250
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001251 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001252 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001253 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001254 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001255 }
1256
Chris Lattner5f9e2722011-07-23 10:55:15 +00001257 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001258
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001259 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001260 exprs.push_back(TheCall->getArg(i));
1261 TheCall->setArg(i, 0);
1262 }
1263
Nate Begemana88dc302009-08-12 02:10:25 +00001264 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001265 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001266 TheCall->getCallee()->getLocStart(),
1267 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001268}
Chris Lattner30ce3442007-12-19 23:59:04 +00001269
Daniel Dunbar4493f792008-07-21 22:59:13 +00001270/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1271// This is declared to take (const void*, ...) and can take two
1272// optional constant int args.
1273bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001274 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001275
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001276 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001277 return Diag(TheCall->getLocEnd(),
1278 diag::err_typecheck_call_too_many_args_at_most)
1279 << 0 /*function call*/ << 3 << NumArgs
1280 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001281
1282 // Argument 0 is checked for us and the remaining arguments must be
1283 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001284 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001285 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001286
Eli Friedman9aef7262009-12-04 00:30:06 +00001287 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001288 if (SemaBuiltinConstantArg(TheCall, i, Result))
1289 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Daniel Dunbar4493f792008-07-21 22:59:13 +00001291 // FIXME: gcc issues a warning and rewrites these to 0. These
1292 // seems especially odd for the third argument since the default
1293 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001294 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001295 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001296 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001297 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001298 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001299 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001300 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001301 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001302 }
1303 }
1304
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001305 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001306}
1307
Eric Christopher691ebc32010-04-17 02:26:23 +00001308/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1309/// TheCall is a constant expression.
1310bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1311 llvm::APSInt &Result) {
1312 Expr *Arg = TheCall->getArg(ArgNum);
1313 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1314 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1315
1316 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1317
1318 if (!Arg->isIntegerConstantExpr(Result, Context))
1319 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001320 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001321
Chris Lattner21fb98e2009-09-23 06:06:36 +00001322 return false;
1323}
1324
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001325/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1326/// int type). This simply type checks that type is one of the defined
1327/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001328// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001329bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001330 llvm::APSInt Result;
1331
1332 // Check constant-ness first.
1333 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1334 return true;
1335
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001336 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001337 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001338 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1339 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001340 }
1341
1342 return false;
1343}
1344
Eli Friedman586d6a82009-05-03 06:04:26 +00001345/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001346/// This checks that val is a constant 1.
1347bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1348 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001349 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001350
Eric Christopher691ebc32010-04-17 02:26:23 +00001351 // TODO: This is less than ideal. Overload this to take a value.
1352 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1353 return true;
1354
1355 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001356 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1357 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1358
1359 return false;
1360}
1361
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001362// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001363bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1364 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001365 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001366 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001367 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001368 if (E->isTypeDependent() || E->isValueDependent())
1369 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001370
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001371 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001372
David Blaikiea73cdcb2012-02-10 21:07:25 +00001373 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1374 // Technically -Wformat-nonliteral does not warn about this case.
1375 // The behavior of printf and friends in this case is implementation
1376 // dependent. Ideally if the format string cannot be null then
1377 // it should have a 'nonnull' attribute in the function prototype.
1378 return true;
1379
Ted Kremenekd30ef872009-01-12 23:09:09 +00001380 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001381 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001382 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001383 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001384 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001385 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001386 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001387 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1388 format_idx, firstDataArg, Type,
1389 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001390 }
1391
1392 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001393 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1394 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001395 }
1396
John McCall56ca35d2011-02-17 10:25:35 +00001397 case Stmt::OpaqueValueExprClass:
1398 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1399 E = src;
1400 goto tryAgain;
1401 }
1402 return false;
1403
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001404 case Stmt::PredefinedExprClass:
1405 // While __func__, etc., are technically not string literals, they
1406 // cannot contain format specifiers and thus are not a security
1407 // liability.
1408 return true;
1409
Ted Kremenek082d9362009-03-20 21:35:28 +00001410 case Stmt::DeclRefExprClass: {
1411 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Ted Kremenek082d9362009-03-20 21:35:28 +00001413 // As an exception, do not flag errors for variables binding to
1414 // const string literals.
1415 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1416 bool isConstant = false;
1417 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001418
Ted Kremenek082d9362009-03-20 21:35:28 +00001419 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1420 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001421 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001422 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001423 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001424 } else if (T->isObjCObjectPointerType()) {
1425 // In ObjC, there is usually no "const ObjectPointer" type,
1426 // so don't check if the pointee type is constant.
1427 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremenek082d9362009-03-20 21:35:28 +00001430 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001431 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001432 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001433 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001434 Type, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Anders Carlssond966a552009-06-28 19:55:58 +00001437 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1438 // special check to see if the format string is a function parameter
1439 // of the function calling the printf function. If the function
1440 // has an attribute indicating it is a printf-like function, then we
1441 // should suppress warnings concerning non-literals being used in a call
1442 // to a vprintf function. For example:
1443 //
1444 // void
1445 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1446 // va_list ap;
1447 // va_start(ap, fmt);
1448 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1449 // ...
1450 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001451 if (HasVAListArg) {
1452 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1453 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1454 int PVIndex = PV->getFunctionScopeIndex() + 1;
1455 for (specific_attr_iterator<FormatAttr>
1456 i = ND->specific_attr_begin<FormatAttr>(),
1457 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1458 FormatAttr *PVFormat = *i;
1459 // adjust for implicit parameter
1460 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1461 if (MD->isInstance())
1462 ++PVIndex;
1463 // We also check if the formats are compatible.
1464 // We can't pass a 'scanf' string to a 'printf' function.
1465 if (PVIndex == PVFormat->getFormatIdx() &&
1466 Type == GetFormatStringType(PVFormat))
1467 return true;
1468 }
1469 }
1470 }
1471 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001472 }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Ted Kremenek082d9362009-03-20 21:35:28 +00001474 return false;
1475 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001476
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001477 case Stmt::CallExprClass:
1478 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001479 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001480 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1481 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1482 unsigned ArgIndex = FA->getFormatIdx();
1483 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1484 if (MD->isInstance())
1485 --ArgIndex;
1486 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001488 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1489 format_idx, firstDataArg, Type,
1490 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001491 }
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Anders Carlsson8f031b32009-06-27 04:05:33 +00001494 return false;
1495 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001496 case Stmt::ObjCStringLiteralClass:
1497 case Stmt::StringLiteralClass: {
1498 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Ted Kremenek082d9362009-03-20 21:35:28 +00001500 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001501 StrE = ObjCFExpr->getString();
1502 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001503 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenekd30ef872009-01-12 23:09:09 +00001505 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001506 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001507 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001508 return true;
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremenekd30ef872009-01-12 23:09:09 +00001511 return false;
1512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Ted Kremenek082d9362009-03-20 21:35:28 +00001514 default:
1515 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001516 }
1517}
1518
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001519void
Mike Stump1eb44332009-09-09 15:08:12 +00001520Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001521 const Expr * const *ExprArgs,
1522 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001523 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1524 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001525 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001526 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001527 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001528 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001529 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001530 }
1531}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001532
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001533Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1534 return llvm::StringSwitch<FormatStringType>(Format->getType())
1535 .Case("scanf", FST_Scanf)
1536 .Cases("printf", "printf0", FST_Printf)
1537 .Cases("NSString", "CFString", FST_NSString)
1538 .Case("strftime", FST_Strftime)
1539 .Case("strfmon", FST_Strfmon)
1540 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1541 .Default(FST_Unknown);
1542}
1543
Ted Kremenek826a3452010-07-16 02:11:22 +00001544/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1545/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001546void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1547 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001548 // The way the format attribute works in GCC, the implicit this argument
1549 // of member functions is counted. However, it doesn't appear in our own
1550 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001551 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001552 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1553 IsCXXMember, TheCall->getRParenLoc(),
1554 TheCall->getCallee()->getSourceRange());
1555}
1556
1557void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1558 unsigned NumArgs, bool IsCXXMember,
1559 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001560 bool HasVAListArg = Format->getFirstArg() == 0;
1561 unsigned format_idx = Format->getFormatIdx() - 1;
1562 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1563 if (IsCXXMember) {
1564 if (format_idx == 0)
1565 return;
1566 --format_idx;
1567 if(firstDataArg != 0)
1568 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001569 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001570 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1571 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001572}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001573
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001574void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1575 bool HasVAListArg, unsigned format_idx,
1576 unsigned firstDataArg, FormatStringType Type,
1577 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001578 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001579 if (format_idx >= NumArgs) {
1580 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001581 return;
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001584 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner59907c42007-08-10 20:18:51 +00001586 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001587 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001588 // Dynamically generated format strings are difficult to
1589 // automatically vet at compile time. Requiring that format strings
1590 // are string literals: (1) permits the checking of format strings by
1591 // the compiler and thereby (2) can practically remove the source of
1592 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001593
Mike Stump1eb44332009-09-09 15:08:12 +00001594 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001595 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001596 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001597 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001598 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001599 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001600 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001601
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001602 // Strftime is particular as it always uses a single 'time' argument,
1603 // so it is safe to pass a non-literal string.
1604 if (Type == FST_Strftime)
1605 return;
1606
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001607 // Do not emit diag when the string param is a macro expansion and the
1608 // format is either NSString or CFString. This is a hack to prevent
1609 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1610 // which are usually used in place of NS and CF string literals.
1611 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1612 return;
1613
Chris Lattner655f1412009-04-29 04:59:47 +00001614 // If there are no arguments specified, warn with -Wformat-security, otherwise
1615 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001616 if (NumArgs == format_idx+1)
1617 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001618 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001619 << OrigFormatExpr->getSourceRange();
1620 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001621 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001622 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001623 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001624}
Ted Kremenek71895b92007-08-14 17:39:48 +00001625
Ted Kremeneke0e53132010-01-28 23:39:18 +00001626namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001627class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1628protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001629 Sema &S;
1630 const StringLiteral *FExpr;
1631 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001632 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001633 const unsigned NumDataArgs;
1634 const bool IsObjCLiteral;
1635 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001636 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001637 const Expr * const *Args;
1638 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001639 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001640 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001641 bool usesPositionalArgs;
1642 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001643 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001644public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001645 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001646 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001647 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001648 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001649 Expr **args, unsigned numArgs,
1650 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001651 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001652 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001653 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001654 IsObjCLiteral(isObjCLiteral), Beg(beg),
1655 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001656 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001657 usesPositionalArgs(false), atFirstArg(true),
1658 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001659 CoveredArgs.resize(numDataArgs);
1660 CoveredArgs.reset();
1661 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001662
Ted Kremenek07d161f2010-01-29 01:50:07 +00001663 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001664
Ted Kremenek826a3452010-07-16 02:11:22 +00001665 void HandleIncompleteSpecifier(const char *startSpecifier,
1666 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001667
1668 void HandleNonStandardLengthModifier(
1669 const analyze_format_string::LengthModifier &LM,
1670 const char *startSpecifier, unsigned specifierLen);
1671
1672 void HandleNonStandardConversionSpecifier(
1673 const analyze_format_string::ConversionSpecifier &CS,
1674 const char *startSpecifier, unsigned specifierLen);
1675
1676 void HandleNonStandardConversionSpecification(
1677 const analyze_format_string::LengthModifier &LM,
1678 const analyze_format_string::ConversionSpecifier &CS,
1679 const char *startSpecifier, unsigned specifierLen);
1680
Hans Wennborgf8562642012-03-09 10:10:54 +00001681 virtual void HandlePosition(const char *startPos, unsigned posLen);
1682
Ted Kremenekefaff192010-02-27 01:41:03 +00001683 virtual void HandleInvalidPosition(const char *startSpecifier,
1684 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001685 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001686
1687 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1688
Ted Kremeneke0e53132010-01-28 23:39:18 +00001689 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001690
Richard Trieu55733de2011-10-28 00:41:25 +00001691 template <typename Range>
1692 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1693 const Expr *ArgumentExpr,
1694 PartialDiagnostic PDiag,
1695 SourceLocation StringLoc,
1696 bool IsStringLocation, Range StringRange,
1697 FixItHint Fixit = FixItHint());
1698
Ted Kremenek826a3452010-07-16 02:11:22 +00001699protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001700 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1701 const char *startSpec,
1702 unsigned specifierLen,
1703 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001704
1705 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1706 const char *startSpec,
1707 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001708
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001709 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001710 CharSourceRange getSpecifierRange(const char *startSpecifier,
1711 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001712 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001713
Ted Kremenek0d277352010-01-29 01:06:55 +00001714 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001715
1716 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1717 const analyze_format_string::ConversionSpecifier &CS,
1718 const char *startSpecifier, unsigned specifierLen,
1719 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001720
1721 template <typename Range>
1722 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1723 bool IsStringLocation, Range StringRange,
1724 FixItHint Fixit = FixItHint());
1725
1726 void CheckPositionalAndNonpositionalArgs(
1727 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001728};
1729}
1730
Ted Kremenek826a3452010-07-16 02:11:22 +00001731SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001732 return OrigFormatExpr->getSourceRange();
1733}
1734
Ted Kremenek826a3452010-07-16 02:11:22 +00001735CharSourceRange CheckFormatHandler::
1736getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001737 SourceLocation Start = getLocationOfByte(startSpecifier);
1738 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1739
1740 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001741 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001742
1743 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001744}
1745
Ted Kremenek826a3452010-07-16 02:11:22 +00001746SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001747 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001748}
1749
Ted Kremenek826a3452010-07-16 02:11:22 +00001750void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1751 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001752 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1753 getLocationOfByte(startSpecifier),
1754 /*IsStringLocation*/true,
1755 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001756}
1757
Hans Wennborg76517422012-02-22 10:17:01 +00001758void CheckFormatHandler::HandleNonStandardLengthModifier(
1759 const analyze_format_string::LengthModifier &LM,
1760 const char *startSpecifier, unsigned specifierLen) {
1761 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001762 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001763 getLocationOfByte(LM.getStart()),
1764 /*IsStringLocation*/true,
1765 getSpecifierRange(startSpecifier, specifierLen));
1766}
1767
1768void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1769 const analyze_format_string::ConversionSpecifier &CS,
1770 const char *startSpecifier, unsigned specifierLen) {
1771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001772 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001773 getLocationOfByte(CS.getStart()),
1774 /*IsStringLocation*/true,
1775 getSpecifierRange(startSpecifier, specifierLen));
1776}
1777
1778void CheckFormatHandler::HandleNonStandardConversionSpecification(
1779 const analyze_format_string::LengthModifier &LM,
1780 const analyze_format_string::ConversionSpecifier &CS,
1781 const char *startSpecifier, unsigned specifierLen) {
1782 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1783 << LM.toString() << CS.toString(),
1784 getLocationOfByte(LM.getStart()),
1785 /*IsStringLocation*/true,
1786 getSpecifierRange(startSpecifier, specifierLen));
1787}
1788
Hans Wennborgf8562642012-03-09 10:10:54 +00001789void CheckFormatHandler::HandlePosition(const char *startPos,
1790 unsigned posLen) {
1791 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1792 getLocationOfByte(startPos),
1793 /*IsStringLocation*/true,
1794 getSpecifierRange(startPos, posLen));
1795}
1796
Ted Kremenekefaff192010-02-27 01:41:03 +00001797void
Ted Kremenek826a3452010-07-16 02:11:22 +00001798CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1799 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001800 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1801 << (unsigned) p,
1802 getLocationOfByte(startPos), /*IsStringLocation*/true,
1803 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001804}
1805
Ted Kremenek826a3452010-07-16 02:11:22 +00001806void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001807 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001808 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1809 getLocationOfByte(startPos),
1810 /*IsStringLocation*/true,
1811 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001812}
1813
Ted Kremenek826a3452010-07-16 02:11:22 +00001814void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001815 if (!IsObjCLiteral) {
1816 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001817 EmitFormatDiagnostic(
1818 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1819 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1820 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001821 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001822}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001823
Ted Kremenek826a3452010-07-16 02:11:22 +00001824const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001825 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001826}
1827
1828void CheckFormatHandler::DoneProcessing() {
1829 // Does the number of data arguments exceed the number of
1830 // format conversions in the format string?
1831 if (!HasVAListArg) {
1832 // Find any arguments that weren't covered.
1833 CoveredArgs.flip();
1834 signed notCoveredArg = CoveredArgs.find_first();
1835 if (notCoveredArg >= 0) {
1836 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001837 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1838 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1839 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001840 }
1841 }
1842}
1843
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001844bool
1845CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1846 SourceLocation Loc,
1847 const char *startSpec,
1848 unsigned specifierLen,
1849 const char *csStart,
1850 unsigned csLen) {
1851
1852 bool keepGoing = true;
1853 if (argIndex < NumDataArgs) {
1854 // Consider the argument coverered, even though the specifier doesn't
1855 // make sense.
1856 CoveredArgs.set(argIndex);
1857 }
1858 else {
1859 // If argIndex exceeds the number of data arguments we
1860 // don't issue a warning because that is just a cascade of warnings (and
1861 // they may have intended '%%' anyway). We don't want to continue processing
1862 // the format string after this point, however, as we will like just get
1863 // gibberish when trying to match arguments.
1864 keepGoing = false;
1865 }
1866
Richard Trieu55733de2011-10-28 00:41:25 +00001867 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1868 << StringRef(csStart, csLen),
1869 Loc, /*IsStringLocation*/true,
1870 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001871
1872 return keepGoing;
1873}
1874
Richard Trieu55733de2011-10-28 00:41:25 +00001875void
1876CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1877 const char *startSpec,
1878 unsigned specifierLen) {
1879 EmitFormatDiagnostic(
1880 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1881 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1882}
1883
Ted Kremenek666a1972010-07-26 19:45:42 +00001884bool
1885CheckFormatHandler::CheckNumArgs(
1886 const analyze_format_string::FormatSpecifier &FS,
1887 const analyze_format_string::ConversionSpecifier &CS,
1888 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1889
1890 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001891 PartialDiagnostic PDiag = FS.usesPositionalArg()
1892 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1893 << (argIndex+1) << NumDataArgs)
1894 : S.PDiag(diag::warn_printf_insufficient_data_args);
1895 EmitFormatDiagnostic(
1896 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1897 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001898 return false;
1899 }
1900 return true;
1901}
1902
Richard Trieu55733de2011-10-28 00:41:25 +00001903template<typename Range>
1904void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1905 SourceLocation Loc,
1906 bool IsStringLocation,
1907 Range StringRange,
1908 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001909 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001910 Loc, IsStringLocation, StringRange, FixIt);
1911}
1912
1913/// \brief If the format string is not within the funcion call, emit a note
1914/// so that the function call and string are in diagnostic messages.
1915///
1916/// \param inFunctionCall if true, the format string is within the function
1917/// call and only one diagnostic message will be produced. Otherwise, an
1918/// extra note will be emitted pointing to location of the format string.
1919///
1920/// \param ArgumentExpr the expression that is passed as the format string
1921/// argument in the function call. Used for getting locations when two
1922/// diagnostics are emitted.
1923///
1924/// \param PDiag the callee should already have provided any strings for the
1925/// diagnostic message. This function only adds locations and fixits
1926/// to diagnostics.
1927///
1928/// \param Loc primary location for diagnostic. If two diagnostics are
1929/// required, one will be at Loc and a new SourceLocation will be created for
1930/// the other one.
1931///
1932/// \param IsStringLocation if true, Loc points to the format string should be
1933/// used for the note. Otherwise, Loc points to the argument list and will
1934/// be used with PDiag.
1935///
1936/// \param StringRange some or all of the string to highlight. This is
1937/// templated so it can accept either a CharSourceRange or a SourceRange.
1938///
1939/// \param Fixit optional fix it hint for the format string.
1940template<typename Range>
1941void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1942 const Expr *ArgumentExpr,
1943 PartialDiagnostic PDiag,
1944 SourceLocation Loc,
1945 bool IsStringLocation,
1946 Range StringRange,
1947 FixItHint FixIt) {
1948 if (InFunctionCall)
1949 S.Diag(Loc, PDiag) << StringRange << FixIt;
1950 else {
1951 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1952 << ArgumentExpr->getSourceRange();
1953 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1954 diag::note_format_string_defined)
1955 << StringRange << FixIt;
1956 }
1957}
1958
Ted Kremenek826a3452010-07-16 02:11:22 +00001959//===--- CHECK: Printf format string checking ------------------------------===//
1960
1961namespace {
1962class CheckPrintfHandler : public CheckFormatHandler {
1963public:
1964 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1965 const Expr *origFormatExpr, unsigned firstDataArg,
1966 unsigned numDataArgs, bool isObjCLiteral,
1967 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001968 Expr **Args, unsigned NumArgs,
1969 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001970 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1971 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001972 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001973
1974
1975 bool HandleInvalidPrintfConversionSpecifier(
1976 const analyze_printf::PrintfSpecifier &FS,
1977 const char *startSpecifier,
1978 unsigned specifierLen);
1979
1980 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1981 const char *startSpecifier,
1982 unsigned specifierLen);
1983
1984 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1985 const char *startSpecifier, unsigned specifierLen);
1986 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1987 const analyze_printf::OptionalAmount &Amt,
1988 unsigned type,
1989 const char *startSpecifier, unsigned specifierLen);
1990 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1991 const analyze_printf::OptionalFlag &flag,
1992 const char *startSpecifier, unsigned specifierLen);
1993 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1994 const analyze_printf::OptionalFlag &ignoredFlag,
1995 const analyze_printf::OptionalFlag &flag,
1996 const char *startSpecifier, unsigned specifierLen);
1997};
1998}
1999
2000bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2001 const analyze_printf::PrintfSpecifier &FS,
2002 const char *startSpecifier,
2003 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002004 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002005 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002006
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002007 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2008 getLocationOfByte(CS.getStart()),
2009 startSpecifier, specifierLen,
2010 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002011}
2012
Ted Kremenek826a3452010-07-16 02:11:22 +00002013bool CheckPrintfHandler::HandleAmount(
2014 const analyze_format_string::OptionalAmount &Amt,
2015 unsigned k, const char *startSpecifier,
2016 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002017
2018 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002019 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002020 unsigned argIndex = Amt.getArgIndex();
2021 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002022 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2023 << k,
2024 getLocationOfByte(Amt.getStart()),
2025 /*IsStringLocation*/true,
2026 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002027 // Don't do any more checking. We will just emit
2028 // spurious errors.
2029 return false;
2030 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002031
Ted Kremenek0d277352010-01-29 01:06:55 +00002032 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002033 // Although not in conformance with C99, we also allow the argument to be
2034 // an 'unsigned int' as that is a reasonably safe case. GCC also
2035 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002036 CoveredArgs.set(argIndex);
2037 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002038 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002039
2040 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2041 assert(ATR.isValid());
2042
2043 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002044 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002045 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002046 << T << Arg->getSourceRange(),
2047 getLocationOfByte(Amt.getStart()),
2048 /*IsStringLocation*/true,
2049 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002050 // Don't do any more checking. We will just emit
2051 // spurious errors.
2052 return false;
2053 }
2054 }
2055 }
2056 return true;
2057}
Ted Kremenek0d277352010-01-29 01:06:55 +00002058
Tom Caree4ee9662010-06-17 19:00:27 +00002059void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002060 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002061 const analyze_printf::OptionalAmount &Amt,
2062 unsigned type,
2063 const char *startSpecifier,
2064 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002065 const analyze_printf::PrintfConversionSpecifier &CS =
2066 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002067
Richard Trieu55733de2011-10-28 00:41:25 +00002068 FixItHint fixit =
2069 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2070 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2071 Amt.getConstantLength()))
2072 : FixItHint();
2073
2074 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2075 << type << CS.toString(),
2076 getLocationOfByte(Amt.getStart()),
2077 /*IsStringLocation*/true,
2078 getSpecifierRange(startSpecifier, specifierLen),
2079 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002080}
2081
Ted Kremenek826a3452010-07-16 02:11:22 +00002082void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002083 const analyze_printf::OptionalFlag &flag,
2084 const char *startSpecifier,
2085 unsigned specifierLen) {
2086 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002087 const analyze_printf::PrintfConversionSpecifier &CS =
2088 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002089 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2090 << flag.toString() << CS.toString(),
2091 getLocationOfByte(flag.getPosition()),
2092 /*IsStringLocation*/true,
2093 getSpecifierRange(startSpecifier, specifierLen),
2094 FixItHint::CreateRemoval(
2095 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002096}
2097
2098void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002099 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002100 const analyze_printf::OptionalFlag &ignoredFlag,
2101 const analyze_printf::OptionalFlag &flag,
2102 const char *startSpecifier,
2103 unsigned specifierLen) {
2104 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002105 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2106 << ignoredFlag.toString() << flag.toString(),
2107 getLocationOfByte(ignoredFlag.getPosition()),
2108 /*IsStringLocation*/true,
2109 getSpecifierRange(startSpecifier, specifierLen),
2110 FixItHint::CreateRemoval(
2111 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002112}
2113
Ted Kremeneke0e53132010-01-28 23:39:18 +00002114bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002115CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002116 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002117 const char *startSpecifier,
2118 unsigned specifierLen) {
2119
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002120 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002121 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002122 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002123
Ted Kremenekbaa40062010-07-19 22:01:06 +00002124 if (FS.consumesDataArgument()) {
2125 if (atFirstArg) {
2126 atFirstArg = false;
2127 usesPositionalArgs = FS.usesPositionalArg();
2128 }
2129 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002130 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2131 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002132 return false;
2133 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002134 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002135
Ted Kremenekefaff192010-02-27 01:41:03 +00002136 // First check if the field width, precision, and conversion specifier
2137 // have matching data arguments.
2138 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2139 startSpecifier, specifierLen)) {
2140 return false;
2141 }
2142
2143 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2144 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002145 return false;
2146 }
2147
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002148 if (!CS.consumesDataArgument()) {
2149 // FIXME: Technically specifying a precision or field width here
2150 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002151 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002152 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002153
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002154 // Consume the argument.
2155 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002156 if (argIndex < NumDataArgs) {
2157 // The check to see if the argIndex is valid will come later.
2158 // We set the bit here because we may exit early from this
2159 // function if we encounter some other error.
2160 CoveredArgs.set(argIndex);
2161 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002162
2163 // Check for using an Objective-C specific conversion specifier
2164 // in a non-ObjC literal.
2165 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002166 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2167 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002168 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002169
Tom Caree4ee9662010-06-17 19:00:27 +00002170 // Check for invalid use of field width
2171 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002172 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002173 startSpecifier, specifierLen);
2174 }
2175
2176 // Check for invalid use of precision
2177 if (!FS.hasValidPrecision()) {
2178 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2179 startSpecifier, specifierLen);
2180 }
2181
2182 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002183 if (!FS.hasValidThousandsGroupingPrefix())
2184 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002185 if (!FS.hasValidLeadingZeros())
2186 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2187 if (!FS.hasValidPlusPrefix())
2188 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002189 if (!FS.hasValidSpacePrefix())
2190 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002191 if (!FS.hasValidAlternativeForm())
2192 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2193 if (!FS.hasValidLeftJustified())
2194 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2195
2196 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002197 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2198 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2199 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002200 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2201 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2202 startSpecifier, specifierLen);
2203
2204 // Check the length modifier is valid with the given conversion specifier.
2205 const LengthModifier &LM = FS.getLengthModifier();
2206 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002207 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2208 << LM.toString() << CS.toString(),
2209 getLocationOfByte(LM.getStart()),
2210 /*IsStringLocation*/true,
2211 getSpecifierRange(startSpecifier, specifierLen),
2212 FixItHint::CreateRemoval(
2213 getSpecifierRange(LM.getStart(),
2214 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002215 if (!FS.hasStandardLengthModifier())
2216 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002217 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002218 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2219 if (!FS.hasStandardLengthConversionCombination())
2220 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2221 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002222
2223 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002224 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002225 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002226 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2227 getLocationOfByte(CS.getStart()),
2228 /*IsStringLocation*/true,
2229 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002230 // Continue checking the other format specifiers.
2231 return true;
2232 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002233
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002234 // The remaining checks depend on the data arguments.
2235 if (HasVAListArg)
2236 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002237
Ted Kremenek666a1972010-07-26 19:45:42 +00002238 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002239 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002240
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002241 // Now type check the data expression that matches the
2242 // format specifier.
2243 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002244 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2245 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002246 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2247 // Check if we didn't match because of an implicit cast from a 'char'
2248 // or 'short' to an 'int'. This is done because printf is a varargs
2249 // function.
2250 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002251 if (ICE->getType() == S.Context.IntTy) {
2252 // All further checking is done on the subexpression.
2253 Ex = ICE->getSubExpr();
2254 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002255 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002256 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002257
2258 // We may be able to offer a FixItHint if it is a supported type.
2259 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002260 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002261 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002262
2263 if (success) {
2264 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002265 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002266 llvm::raw_svector_ostream os(buf);
2267 fixedFS.toString(os);
2268
Richard Trieu55733de2011-10-28 00:41:25 +00002269 EmitFormatDiagnostic(
2270 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002271 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002272 << Ex->getSourceRange(),
2273 getLocationOfByte(CS.getStart()),
2274 /*IsStringLocation*/true,
2275 getSpecifierRange(startSpecifier, specifierLen),
2276 FixItHint::CreateReplacement(
2277 getSpecifierRange(startSpecifier, specifierLen),
2278 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002279 }
2280 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002281 EmitFormatDiagnostic(
2282 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2283 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2284 << getSpecifierRange(startSpecifier, specifierLen)
2285 << Ex->getSourceRange(),
2286 getLocationOfByte(CS.getStart()),
2287 true,
2288 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002289 }
2290 }
2291
Ted Kremeneke0e53132010-01-28 23:39:18 +00002292 return true;
2293}
2294
Ted Kremenek826a3452010-07-16 02:11:22 +00002295//===--- CHECK: Scanf format string checking ------------------------------===//
2296
2297namespace {
2298class CheckScanfHandler : public CheckFormatHandler {
2299public:
2300 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2301 const Expr *origFormatExpr, unsigned firstDataArg,
2302 unsigned numDataArgs, bool isObjCLiteral,
2303 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002304 Expr **Args, unsigned NumArgs,
2305 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002306 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2307 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002308 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002309
2310 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2311 const char *startSpecifier,
2312 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002313
2314 bool HandleInvalidScanfConversionSpecifier(
2315 const analyze_scanf::ScanfSpecifier &FS,
2316 const char *startSpecifier,
2317 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002318
2319 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002320};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002321}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002322
Ted Kremenekb7c21012010-07-16 18:28:03 +00002323void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2324 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002325 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2326 getLocationOfByte(end), /*IsStringLocation*/true,
2327 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002328}
2329
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002330bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2331 const analyze_scanf::ScanfSpecifier &FS,
2332 const char *startSpecifier,
2333 unsigned specifierLen) {
2334
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002335 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002336 FS.getConversionSpecifier();
2337
2338 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2339 getLocationOfByte(CS.getStart()),
2340 startSpecifier, specifierLen,
2341 CS.getStart(), CS.getLength());
2342}
2343
Ted Kremenek826a3452010-07-16 02:11:22 +00002344bool CheckScanfHandler::HandleScanfSpecifier(
2345 const analyze_scanf::ScanfSpecifier &FS,
2346 const char *startSpecifier,
2347 unsigned specifierLen) {
2348
2349 using namespace analyze_scanf;
2350 using namespace analyze_format_string;
2351
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002352 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002353
Ted Kremenekbaa40062010-07-19 22:01:06 +00002354 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2355 // be used to decide if we are using positional arguments consistently.
2356 if (FS.consumesDataArgument()) {
2357 if (atFirstArg) {
2358 atFirstArg = false;
2359 usesPositionalArgs = FS.usesPositionalArg();
2360 }
2361 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002362 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2363 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002364 return false;
2365 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002366 }
2367
2368 // Check if the field with is non-zero.
2369 const OptionalAmount &Amt = FS.getFieldWidth();
2370 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2371 if (Amt.getConstantAmount() == 0) {
2372 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2373 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002374 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2375 getLocationOfByte(Amt.getStart()),
2376 /*IsStringLocation*/true, R,
2377 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002378 }
2379 }
2380
2381 if (!FS.consumesDataArgument()) {
2382 // FIXME: Technically specifying a precision or field width here
2383 // makes no sense. Worth issuing a warning at some point.
2384 return true;
2385 }
2386
2387 // Consume the argument.
2388 unsigned argIndex = FS.getArgIndex();
2389 if (argIndex < NumDataArgs) {
2390 // The check to see if the argIndex is valid will come later.
2391 // We set the bit here because we may exit early from this
2392 // function if we encounter some other error.
2393 CoveredArgs.set(argIndex);
2394 }
2395
Ted Kremenek1e51c202010-07-20 20:04:47 +00002396 // Check the length modifier is valid with the given conversion specifier.
2397 const LengthModifier &LM = FS.getLengthModifier();
2398 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002399 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2400 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2401 << LM.toString() << CS.toString()
2402 << getSpecifierRange(startSpecifier, specifierLen),
2403 getLocationOfByte(LM.getStart()),
2404 /*IsStringLocation*/true, R,
2405 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002406 }
2407
Hans Wennborg76517422012-02-22 10:17:01 +00002408 if (!FS.hasStandardLengthModifier())
2409 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002410 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002411 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2412 if (!FS.hasStandardLengthConversionCombination())
2413 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2414 specifierLen);
2415
Ted Kremenek826a3452010-07-16 02:11:22 +00002416 // The remaining checks depend on the data arguments.
2417 if (HasVAListArg)
2418 return true;
2419
Ted Kremenek666a1972010-07-26 19:45:42 +00002420 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002421 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002422
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002423 // Check that the argument type matches the format specifier.
2424 const Expr *Ex = getDataArg(argIndex);
2425 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2426 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2427 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002428 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002429 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002430
2431 if (success) {
2432 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002433 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002434 llvm::raw_svector_ostream os(buf);
2435 fixedFS.toString(os);
2436
2437 EmitFormatDiagnostic(
2438 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2439 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2440 << Ex->getSourceRange(),
2441 getLocationOfByte(CS.getStart()),
2442 /*IsStringLocation*/true,
2443 getSpecifierRange(startSpecifier, specifierLen),
2444 FixItHint::CreateReplacement(
2445 getSpecifierRange(startSpecifier, specifierLen),
2446 os.str()));
2447 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002448 EmitFormatDiagnostic(
2449 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002450 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002451 << Ex->getSourceRange(),
2452 getLocationOfByte(CS.getStart()),
2453 /*IsStringLocation*/true,
2454 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002455 }
2456 }
2457
Ted Kremenek826a3452010-07-16 02:11:22 +00002458 return true;
2459}
2460
2461void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002462 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002463 Expr **Args, unsigned NumArgs,
2464 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002465 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002466 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002467
Ted Kremeneke0e53132010-01-28 23:39:18 +00002468 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002469 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002470 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002471 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002472 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2473 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002474 return;
2475 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002476
Ted Kremeneke0e53132010-01-28 23:39:18 +00002477 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002479 const char *Str = StrRef.data();
2480 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002481 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002482
Ted Kremeneke0e53132010-01-28 23:39:18 +00002483 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002484 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002485 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002486 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002487 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2488 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002489 return;
2490 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002491
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002492 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002493 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002494 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002495 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002496 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002497
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002498 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002499 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002500 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002501 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002502 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002503 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002504 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002505 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002506
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002507 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002508 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002509 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002510 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002511}
2512
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002513//===--- CHECK: Standard memory functions ---------------------------------===//
2514
Douglas Gregor2a053a32011-05-03 20:05:22 +00002515/// \brief Determine whether the given type is a dynamic class type (e.g.,
2516/// whether it has a vtable).
2517static bool isDynamicClassType(QualType T) {
2518 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2519 if (CXXRecordDecl *Definition = Record->getDefinition())
2520 if (Definition->isDynamicClass())
2521 return true;
2522
2523 return false;
2524}
2525
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002526/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002527/// otherwise returns NULL.
2528static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002529 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002530 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2531 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2532 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002533
Chandler Carruth000d4282011-06-16 09:09:40 +00002534 return 0;
2535}
2536
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002537/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002538static QualType getSizeOfArgType(const Expr* E) {
2539 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2540 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2541 if (SizeOf->getKind() == clang::UETT_SizeOf)
2542 return SizeOf->getTypeOfArgument();
2543
2544 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002545}
2546
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002547/// \brief Check for dangerous or invalid arguments to memset().
2548///
Chandler Carruth929f0132011-06-03 06:23:57 +00002549/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002550/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2551/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002552///
2553/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002554void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002555 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002556 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002557 assert(BId != 0);
2558
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002559 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002560 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002561 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002562 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002563 return;
2564
Anna Zaks0a151a12012-01-17 00:37:07 +00002565 unsigned LastArg = (BId == Builtin::BImemset ||
2566 BId == Builtin::BIstrndup ? 1 : 2);
2567 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002568 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002569
2570 // We have special checking when the length is a sizeof expression.
2571 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2572 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2573 llvm::FoldingSetNodeID SizeOfArgID;
2574
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002575 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2576 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002577 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002578
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002579 QualType DestTy = Dest->getType();
2580 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2581 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002582
Chandler Carruth000d4282011-06-16 09:09:40 +00002583 // Never warn about void type pointers. This can be used to suppress
2584 // false positives.
2585 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002586 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002587
Chandler Carruth000d4282011-06-16 09:09:40 +00002588 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2589 // actually comparing the expressions for equality. Because computing the
2590 // expression IDs can be expensive, we only do this if the diagnostic is
2591 // enabled.
2592 if (SizeOfArg &&
2593 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2594 SizeOfArg->getExprLoc())) {
2595 // We only compute IDs for expressions if the warning is enabled, and
2596 // cache the sizeof arg's ID.
2597 if (SizeOfArgID == llvm::FoldingSetNodeID())
2598 SizeOfArg->Profile(SizeOfArgID, Context, true);
2599 llvm::FoldingSetNodeID DestID;
2600 Dest->Profile(DestID, Context, true);
2601 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002602 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2603 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002604 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2605 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2606 if (UnaryOp->getOpcode() == UO_AddrOf)
2607 ActionIdx = 1; // If its an address-of operator, just remove it.
2608 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2609 ActionIdx = 2; // If the pointee's size is sizeof(char),
2610 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002611 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002612 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002613 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2614 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002615 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002616 << Dest->getSourceRange()
2617 << SizeOfArg->getSourceRange());
2618 break;
2619 }
2620 }
2621
2622 // Also check for cases where the sizeof argument is the exact same
2623 // type as the memory argument, and where it points to a user-defined
2624 // record type.
2625 if (SizeOfArgTy != QualType()) {
2626 if (PointeeTy->isRecordType() &&
2627 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2628 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2629 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2630 << FnName << SizeOfArgTy << ArgIdx
2631 << PointeeTy << Dest->getSourceRange()
2632 << LenExpr->getSourceRange());
2633 break;
2634 }
Nico Webere4a1c642011-06-14 16:14:58 +00002635 }
2636
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002637 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002638 if (isDynamicClassType(PointeeTy)) {
2639
2640 unsigned OperationType = 0;
2641 // "overwritten" if we're warning about the destination for any call
2642 // but memcmp; otherwise a verb appropriate to the call.
2643 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2644 if (BId == Builtin::BImemcpy)
2645 OperationType = 1;
2646 else if(BId == Builtin::BImemmove)
2647 OperationType = 2;
2648 else if (BId == Builtin::BImemcmp)
2649 OperationType = 3;
2650 }
2651
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002652 DiagRuntimeBehavior(
2653 Dest->getExprLoc(), Dest,
2654 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002655 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002656 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002657 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002658 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002659 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2660 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002661 DiagRuntimeBehavior(
2662 Dest->getExprLoc(), Dest,
2663 PDiag(diag::warn_arc_object_memaccess)
2664 << ArgIdx << FnName << PointeeTy
2665 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002666 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002667 continue;
John McCallf85e1932011-06-15 23:02:42 +00002668
2669 DiagRuntimeBehavior(
2670 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002671 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002672 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2673 break;
2674 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002675 }
2676}
2677
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002678// A little helper routine: ignore addition and subtraction of integer literals.
2679// This intentionally does not ignore all integer constant expressions because
2680// we don't want to remove sizeof().
2681static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2682 Ex = Ex->IgnoreParenCasts();
2683
2684 for (;;) {
2685 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2686 if (!BO || !BO->isAdditiveOp())
2687 break;
2688
2689 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2690 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2691
2692 if (isa<IntegerLiteral>(RHS))
2693 Ex = LHS;
2694 else if (isa<IntegerLiteral>(LHS))
2695 Ex = RHS;
2696 else
2697 break;
2698 }
2699
2700 return Ex;
2701}
2702
2703// Warn if the user has made the 'size' argument to strlcpy or strlcat
2704// be the size of the source, instead of the destination.
2705void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2706 IdentifierInfo *FnName) {
2707
2708 // Don't crash if the user has the wrong number of arguments
2709 if (Call->getNumArgs() != 3)
2710 return;
2711
2712 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2713 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2714 const Expr *CompareWithSrc = NULL;
2715
2716 // Look for 'strlcpy(dst, x, sizeof(x))'
2717 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2718 CompareWithSrc = Ex;
2719 else {
2720 // Look for 'strlcpy(dst, x, strlen(x))'
2721 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002722 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002723 && SizeCall->getNumArgs() == 1)
2724 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2725 }
2726 }
2727
2728 if (!CompareWithSrc)
2729 return;
2730
2731 // Determine if the argument to sizeof/strlen is equal to the source
2732 // argument. In principle there's all kinds of things you could do
2733 // here, for instance creating an == expression and evaluating it with
2734 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2735 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2736 if (!SrcArgDRE)
2737 return;
2738
2739 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2740 if (!CompareWithSrcDRE ||
2741 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2742 return;
2743
2744 const Expr *OriginalSizeArg = Call->getArg(2);
2745 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2746 << OriginalSizeArg->getSourceRange() << FnName;
2747
2748 // Output a FIXIT hint if the destination is an array (rather than a
2749 // pointer to an array). This could be enhanced to handle some
2750 // pointers if we know the actual size, like if DstArg is 'array+2'
2751 // we could say 'sizeof(array)-2'.
2752 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002753 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002754
Ted Kremenek8f746222011-08-18 22:48:41 +00002755 // Only handle constant-sized or VLAs, but not flexible members.
2756 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2757 // Only issue the FIXIT for arrays of size > 1.
2758 if (CAT->getSize().getSExtValue() <= 1)
2759 return;
2760 } else if (!DstArgTy->isVariableArrayType()) {
2761 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002762 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002763
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002764 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002765 llvm::raw_svector_ostream OS(sizeString);
2766 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002767 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002768 OS << ")";
2769
2770 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2771 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2772 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002773}
2774
Anna Zaksc36bedc2012-02-01 19:08:57 +00002775/// Check if two expressions refer to the same declaration.
2776static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2777 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2778 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2779 return D1->getDecl() == D2->getDecl();
2780 return false;
2781}
2782
2783static const Expr *getStrlenExprArg(const Expr *E) {
2784 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2785 const FunctionDecl *FD = CE->getDirectCallee();
2786 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2787 return 0;
2788 return CE->getArg(0)->IgnoreParenCasts();
2789 }
2790 return 0;
2791}
2792
2793// Warn on anti-patterns as the 'size' argument to strncat.
2794// The correct size argument should look like following:
2795// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2796void Sema::CheckStrncatArguments(const CallExpr *CE,
2797 IdentifierInfo *FnName) {
2798 // Don't crash if the user has the wrong number of arguments.
2799 if (CE->getNumArgs() < 3)
2800 return;
2801 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2802 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2803 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2804
2805 // Identify common expressions, which are wrongly used as the size argument
2806 // to strncat and may lead to buffer overflows.
2807 unsigned PatternType = 0;
2808 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2809 // - sizeof(dst)
2810 if (referToTheSameDecl(SizeOfArg, DstArg))
2811 PatternType = 1;
2812 // - sizeof(src)
2813 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2814 PatternType = 2;
2815 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2816 if (BE->getOpcode() == BO_Sub) {
2817 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2818 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2819 // - sizeof(dst) - strlen(dst)
2820 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2821 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2822 PatternType = 1;
2823 // - sizeof(src) - (anything)
2824 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2825 PatternType = 2;
2826 }
2827 }
2828
2829 if (PatternType == 0)
2830 return;
2831
Anna Zaksafdb0412012-02-03 01:27:37 +00002832 // Generate the diagnostic.
2833 SourceLocation SL = LenArg->getLocStart();
2834 SourceRange SR = LenArg->getSourceRange();
2835 SourceManager &SM = PP.getSourceManager();
2836
2837 // If the function is defined as a builtin macro, do not show macro expansion.
2838 if (SM.isMacroArgExpansion(SL)) {
2839 SL = SM.getSpellingLoc(SL);
2840 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2841 SM.getSpellingLoc(SR.getEnd()));
2842 }
2843
Anna Zaksc36bedc2012-02-01 19:08:57 +00002844 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002845 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002846 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002847 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002848
2849 // Output a FIXIT hint if the destination is an array (rather than a
2850 // pointer to an array). This could be enhanced to handle some
2851 // pointers if we know the actual size, like if DstArg is 'array+2'
2852 // we could say 'sizeof(array)-2'.
2853 QualType DstArgTy = DstArg->getType();
2854
2855 // Only handle constant-sized or VLAs, but not flexible members.
2856 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2857 // Only issue the FIXIT for arrays of size > 1.
2858 if (CAT->getSize().getSExtValue() <= 1)
2859 return;
2860 } else if (!DstArgTy->isVariableArrayType()) {
2861 return;
2862 }
2863
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002864 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002865 llvm::raw_svector_ostream OS(sizeString);
2866 OS << "sizeof(";
2867 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2868 OS << ") - ";
2869 OS << "strlen(";
2870 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2871 OS << ") - 1";
2872
Anna Zaksafdb0412012-02-03 01:27:37 +00002873 Diag(SL, diag::note_strncat_wrong_size)
2874 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00002875}
2876
Ted Kremenek06de2762007-08-17 16:46:58 +00002877//===--- CHECK: Return Address of Stack Variable --------------------------===//
2878
Chris Lattner5f9e2722011-07-23 10:55:15 +00002879static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2880static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002881
2882/// CheckReturnStackAddr - Check if a return statement returns the address
2883/// of a stack variable.
2884void
2885Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2886 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002888 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002889 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002890
2891 // Perform checking for returned stack addresses, local blocks,
2892 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002893 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002894 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002895 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002896 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002897 stackE = EvalVal(RetValExp, refVars);
2898 }
2899
2900 if (stackE == 0)
2901 return; // Nothing suspicious was found.
2902
2903 SourceLocation diagLoc;
2904 SourceRange diagRange;
2905 if (refVars.empty()) {
2906 diagLoc = stackE->getLocStart();
2907 diagRange = stackE->getSourceRange();
2908 } else {
2909 // We followed through a reference variable. 'stackE' contains the
2910 // problematic expression but we will warn at the return statement pointing
2911 // at the reference variable. We will later display the "trail" of
2912 // reference variables using notes.
2913 diagLoc = refVars[0]->getLocStart();
2914 diagRange = refVars[0]->getSourceRange();
2915 }
2916
2917 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2918 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2919 : diag::warn_ret_stack_addr)
2920 << DR->getDecl()->getDeclName() << diagRange;
2921 } else if (isa<BlockExpr>(stackE)) { // local block.
2922 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2923 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2924 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2925 } else { // local temporary.
2926 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2927 : diag::warn_ret_local_temp_addr)
2928 << diagRange;
2929 }
2930
2931 // Display the "trail" of reference variables that we followed until we
2932 // found the problematic expression using notes.
2933 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2934 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2935 // If this var binds to another reference var, show the range of the next
2936 // var, otherwise the var binds to the problematic expression, in which case
2937 // show the range of the expression.
2938 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2939 : stackE->getSourceRange();
2940 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2941 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002942 }
2943}
2944
2945/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2946/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002947/// to a location on the stack, a local block, an address of a label, or a
2948/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002949/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002950/// encounter a subexpression that (1) clearly does not lead to one of the
2951/// above problematic expressions (2) is something we cannot determine leads to
2952/// a problematic expression based on such local checking.
2953///
2954/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2955/// the expression that they point to. Such variables are added to the
2956/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002957///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002958/// EvalAddr processes expressions that are pointers that are used as
2959/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002960/// At the base case of the recursion is a check for the above problematic
2961/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002962///
2963/// This implementation handles:
2964///
2965/// * pointer-to-pointer casts
2966/// * implicit conversions from array references to pointers
2967/// * taking the address of fields
2968/// * arbitrary interplay between "&" and "*" operators
2969/// * pointer arithmetic from an address of a stack variable
2970/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002971static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002972 if (E->isTypeDependent())
2973 return NULL;
2974
Ted Kremenek06de2762007-08-17 16:46:58 +00002975 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002976 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002977 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002978 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002979 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Peter Collingbournef111d932011-04-15 00:35:48 +00002981 E = E->IgnoreParens();
2982
Ted Kremenek06de2762007-08-17 16:46:58 +00002983 // Our "symbolic interpreter" is just a dispatch off the currently
2984 // viewed AST node. We then recursively traverse the AST by calling
2985 // EvalAddr and EvalVal appropriately.
2986 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002987 case Stmt::DeclRefExprClass: {
2988 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2989
2990 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2991 // If this is a reference variable, follow through to the expression that
2992 // it points to.
2993 if (V->hasLocalStorage() &&
2994 V->getType()->isReferenceType() && V->hasInit()) {
2995 // Add the reference variable to the "trail".
2996 refVars.push_back(DR);
2997 return EvalAddr(V->getInit(), refVars);
2998 }
2999
3000 return NULL;
3001 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003002
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003003 case Stmt::UnaryOperatorClass: {
3004 // The only unary operator that make sense to handle here
3005 // is AddrOf. All others don't make sense as pointers.
3006 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003007
John McCall2de56d12010-08-25 11:45:40 +00003008 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003009 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003010 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003011 return NULL;
3012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003014 case Stmt::BinaryOperatorClass: {
3015 // Handle pointer arithmetic. All other binary operators are not valid
3016 // in this context.
3017 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003018 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003019
John McCall2de56d12010-08-25 11:45:40 +00003020 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003021 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003023 Expr *Base = B->getLHS();
3024
3025 // Determine which argument is the real pointer base. It could be
3026 // the RHS argument instead of the LHS.
3027 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003029 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003030 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003031 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003032
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003033 // For conditional operators we need to see if either the LHS or RHS are
3034 // valid DeclRefExpr*s. If one of them is valid, we return it.
3035 case Stmt::ConditionalOperatorClass: {
3036 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003038 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003039 if (Expr *lhsExpr = C->getLHS()) {
3040 // In C++, we can have a throw-expression, which has 'void' type.
3041 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003042 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003043 return LHS;
3044 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003045
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003046 // In C++, we can have a throw-expression, which has 'void' type.
3047 if (C->getRHS()->getType()->isVoidType())
3048 return NULL;
3049
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003050 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003051 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003052
3053 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003054 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003055 return E; // local block.
3056 return NULL;
3057
3058 case Stmt::AddrLabelExprClass:
3059 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003060
John McCall80ee6e82011-11-10 05:35:25 +00003061 case Stmt::ExprWithCleanupsClass:
3062 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3063
Ted Kremenek54b52742008-08-07 00:49:01 +00003064 // For casts, we need to handle conversions from arrays to
3065 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003066 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003067 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003068 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003069 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003070 case Stmt::CXXStaticCastExprClass:
3071 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003072 case Stmt::CXXConstCastExprClass:
3073 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003074 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3075 switch (cast<CastExpr>(E)->getCastKind()) {
3076 case CK_BitCast:
3077 case CK_LValueToRValue:
3078 case CK_NoOp:
3079 case CK_BaseToDerived:
3080 case CK_DerivedToBase:
3081 case CK_UncheckedDerivedToBase:
3082 case CK_Dynamic:
3083 case CK_CPointerToObjCPointerCast:
3084 case CK_BlockPointerToObjCPointerCast:
3085 case CK_AnyPointerToBlockPointerCast:
3086 return EvalAddr(SubExpr, refVars);
3087
3088 case CK_ArrayToPointerDecay:
3089 return EvalVal(SubExpr, refVars);
3090
3091 default:
3092 return 0;
3093 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003094 }
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Douglas Gregor03e80032011-06-21 17:03:29 +00003096 case Stmt::MaterializeTemporaryExprClass:
3097 if (Expr *Result = EvalAddr(
3098 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3099 refVars))
3100 return Result;
3101
3102 return E;
3103
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003104 // Everything else: we simply don't reason about them.
3105 default:
3106 return NULL;
3107 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003108}
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Ted Kremenek06de2762007-08-17 16:46:58 +00003110
3111/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3112/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003113static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003114do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003115 // We should only be called for evaluating non-pointer expressions, or
3116 // expressions with a pointer type that are not used as references but instead
3117 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Ted Kremenek06de2762007-08-17 16:46:58 +00003119 // Our "symbolic interpreter" is just a dispatch off the currently
3120 // viewed AST node. We then recursively traverse the AST by calling
3121 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003122
3123 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003124 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003125 case Stmt::ImplicitCastExprClass: {
3126 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003127 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003128 E = IE->getSubExpr();
3129 continue;
3130 }
3131 return NULL;
3132 }
3133
John McCall80ee6e82011-11-10 05:35:25 +00003134 case Stmt::ExprWithCleanupsClass:
3135 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3136
Douglas Gregora2813ce2009-10-23 18:54:35 +00003137 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003138 // When we hit a DeclRefExpr we are looking at code that refers to a
3139 // variable's name. If it's not a reference variable we check if it has
3140 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003141 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Ted Kremenek06de2762007-08-17 16:46:58 +00003143 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003144 if (V->hasLocalStorage()) {
3145 if (!V->getType()->isReferenceType())
3146 return DR;
3147
3148 // Reference variable, follow through to the expression that
3149 // it points to.
3150 if (V->hasInit()) {
3151 // Add the reference variable to the "trail".
3152 refVars.push_back(DR);
3153 return EvalVal(V->getInit(), refVars);
3154 }
3155 }
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Ted Kremenek06de2762007-08-17 16:46:58 +00003157 return NULL;
3158 }
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Ted Kremenek06de2762007-08-17 16:46:58 +00003160 case Stmt::UnaryOperatorClass: {
3161 // The only unary operator that make sense to handle here
3162 // is Deref. All others don't resolve to a "name." This includes
3163 // handling all sorts of rvalues passed to a unary operator.
3164 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003165
John McCall2de56d12010-08-25 11:45:40 +00003166 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003167 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003168
3169 return NULL;
3170 }
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Ted Kremenek06de2762007-08-17 16:46:58 +00003172 case Stmt::ArraySubscriptExprClass: {
3173 // Array subscripts are potential references to data on the stack. We
3174 // retrieve the DeclRefExpr* for the array variable if it indeed
3175 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003176 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Ted Kremenek06de2762007-08-17 16:46:58 +00003179 case Stmt::ConditionalOperatorClass: {
3180 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003181 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003182 ConditionalOperator *C = cast<ConditionalOperator>(E);
3183
Anders Carlsson39073232007-11-30 19:04:31 +00003184 // Handle the GNU extension for missing LHS.
3185 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003186 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003187 return LHS;
3188
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003189 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003190 }
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Ted Kremenek06de2762007-08-17 16:46:58 +00003192 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003193 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003194 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Ted Kremenek06de2762007-08-17 16:46:58 +00003196 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003197 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003198 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003199
3200 // Check whether the member type is itself a reference, in which case
3201 // we're not going to refer to the member, but to what the member refers to.
3202 if (M->getMemberDecl()->getType()->isReferenceType())
3203 return NULL;
3204
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003205 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003206 }
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Douglas Gregor03e80032011-06-21 17:03:29 +00003208 case Stmt::MaterializeTemporaryExprClass:
3209 if (Expr *Result = EvalVal(
3210 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3211 refVars))
3212 return Result;
3213
3214 return E;
3215
Ted Kremenek06de2762007-08-17 16:46:58 +00003216 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003217 // Check that we don't return or take the address of a reference to a
3218 // temporary. This is only useful in C++.
3219 if (!E->isTypeDependent() && E->isRValue())
3220 return E;
3221
3222 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003223 return NULL;
3224 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003225} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003226}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003227
3228//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3229
3230/// Check for comparisons of floating point operands using != and ==.
3231/// Issue a warning if these are no self-comparisons, as they are not likely
3232/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003233void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003234 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Richard Trieudd225092011-09-15 21:56:47 +00003236 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3237 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003238
3239 // Special case: check for x == x (which is OK).
3240 // Do not emit warnings for such cases.
3241 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3242 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3243 if (DRL->getDecl() == DRR->getDecl())
3244 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003245
3246
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003247 // Special case: check for comparisons against literals that can be exactly
3248 // represented by APFloat. In such cases, do not emit a warning. This
3249 // is a heuristic: often comparison against such literals are used to
3250 // detect if a value in a variable has not changed. This clearly can
3251 // lead to false negatives.
3252 if (EmitWarning) {
3253 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3254 if (FLL->isExact())
3255 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003256 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003257 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3258 if (FLR->isExact())
3259 EmitWarning = false;
3260 }
3261 }
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003263 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003264 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003265 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003266 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003267 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Sebastian Redl0eb23302009-01-19 00:08:26 +00003269 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003270 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003271 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003272 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003274 // Emit the diagnostic.
3275 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003276 Diag(Loc, diag::warn_floatingpoint_eq)
3277 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003278}
John McCallba26e582010-01-04 23:21:16 +00003279
John McCallf2370c92010-01-06 05:24:50 +00003280//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3281//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003282
John McCallf2370c92010-01-06 05:24:50 +00003283namespace {
John McCallba26e582010-01-04 23:21:16 +00003284
John McCallf2370c92010-01-06 05:24:50 +00003285/// Structure recording the 'active' range of an integer-valued
3286/// expression.
3287struct IntRange {
3288 /// The number of bits active in the int.
3289 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003290
John McCallf2370c92010-01-06 05:24:50 +00003291 /// True if the int is known not to have negative values.
3292 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003293
John McCallf2370c92010-01-06 05:24:50 +00003294 IntRange(unsigned Width, bool NonNegative)
3295 : Width(Width), NonNegative(NonNegative)
3296 {}
John McCallba26e582010-01-04 23:21:16 +00003297
John McCall1844a6e2010-11-10 23:38:19 +00003298 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003299 static IntRange forBoolType() {
3300 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003301 }
3302
John McCall1844a6e2010-11-10 23:38:19 +00003303 /// Returns the range of an opaque value of the given integral type.
3304 static IntRange forValueOfType(ASTContext &C, QualType T) {
3305 return forValueOfCanonicalType(C,
3306 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003307 }
3308
John McCall1844a6e2010-11-10 23:38:19 +00003309 /// Returns the range of an opaque value of a canonical integral type.
3310 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003311 assert(T->isCanonicalUnqualified());
3312
3313 if (const VectorType *VT = dyn_cast<VectorType>(T))
3314 T = VT->getElementType().getTypePtr();
3315 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3316 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003317
John McCall091f23f2010-11-09 22:22:12 +00003318 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003319 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3320 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003321 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003322 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3323
John McCall323ed742010-05-06 08:58:33 +00003324 unsigned NumPositive = Enum->getNumPositiveBits();
3325 unsigned NumNegative = Enum->getNumNegativeBits();
3326
3327 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3328 }
John McCallf2370c92010-01-06 05:24:50 +00003329
3330 const BuiltinType *BT = cast<BuiltinType>(T);
3331 assert(BT->isInteger());
3332
3333 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3334 }
3335
John McCall1844a6e2010-11-10 23:38:19 +00003336 /// Returns the "target" range of a canonical integral type, i.e.
3337 /// the range of values expressible in the type.
3338 ///
3339 /// This matches forValueOfCanonicalType except that enums have the
3340 /// full range of their type, not the range of their enumerators.
3341 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3342 assert(T->isCanonicalUnqualified());
3343
3344 if (const VectorType *VT = dyn_cast<VectorType>(T))
3345 T = VT->getElementType().getTypePtr();
3346 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3347 T = CT->getElementType().getTypePtr();
3348 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003349 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003350
3351 const BuiltinType *BT = cast<BuiltinType>(T);
3352 assert(BT->isInteger());
3353
3354 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3355 }
3356
3357 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003358 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003359 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003360 L.NonNegative && R.NonNegative);
3361 }
3362
John McCall1844a6e2010-11-10 23:38:19 +00003363 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003364 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003365 return IntRange(std::min(L.Width, R.Width),
3366 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003367 }
3368};
3369
Ted Kremenek0692a192012-01-31 05:37:37 +00003370static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3371 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003372 if (value.isSigned() && value.isNegative())
3373 return IntRange(value.getMinSignedBits(), false);
3374
3375 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003376 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003377
3378 // isNonNegative() just checks the sign bit without considering
3379 // signedness.
3380 return IntRange(value.getActiveBits(), true);
3381}
3382
Ted Kremenek0692a192012-01-31 05:37:37 +00003383static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3384 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003385 if (result.isInt())
3386 return GetValueRange(C, result.getInt(), MaxWidth);
3387
3388 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003389 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3390 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3391 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3392 R = IntRange::join(R, El);
3393 }
John McCallf2370c92010-01-06 05:24:50 +00003394 return R;
3395 }
3396
3397 if (result.isComplexInt()) {
3398 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3399 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3400 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003401 }
3402
3403 // This can happen with lossless casts to intptr_t of "based" lvalues.
3404 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003405 // FIXME: The only reason we need to pass the type in here is to get
3406 // the sign right on this one case. It would be nice if APValue
3407 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003408 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003409 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003410}
John McCallf2370c92010-01-06 05:24:50 +00003411
3412/// Pseudo-evaluate the given integer expression, estimating the
3413/// range of values it might take.
3414///
3415/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003416static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003417 E = E->IgnoreParens();
3418
3419 // Try a full evaluation first.
3420 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003421 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003422 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003423
3424 // I think we only want to look through implicit casts here; if the
3425 // user has an explicit widening cast, we should treat the value as
3426 // being of the new, wider type.
3427 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003428 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003429 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3430
John McCall1844a6e2010-11-10 23:38:19 +00003431 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003432
John McCall2de56d12010-08-25 11:45:40 +00003433 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003434
John McCallf2370c92010-01-06 05:24:50 +00003435 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003436 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003437 return OutputTypeRange;
3438
3439 IntRange SubRange
3440 = GetExprRange(C, CE->getSubExpr(),
3441 std::min(MaxWidth, OutputTypeRange.Width));
3442
3443 // Bail out if the subexpr's range is as wide as the cast type.
3444 if (SubRange.Width >= OutputTypeRange.Width)
3445 return OutputTypeRange;
3446
3447 // Otherwise, we take the smaller width, and we're non-negative if
3448 // either the output type or the subexpr is.
3449 return IntRange(SubRange.Width,
3450 SubRange.NonNegative || OutputTypeRange.NonNegative);
3451 }
3452
3453 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3454 // If we can fold the condition, just take that operand.
3455 bool CondResult;
3456 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3457 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3458 : CO->getFalseExpr(),
3459 MaxWidth);
3460
3461 // Otherwise, conservatively merge.
3462 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3463 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3464 return IntRange::join(L, R);
3465 }
3466
3467 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3468 switch (BO->getOpcode()) {
3469
3470 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003471 case BO_LAnd:
3472 case BO_LOr:
3473 case BO_LT:
3474 case BO_GT:
3475 case BO_LE:
3476 case BO_GE:
3477 case BO_EQ:
3478 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003479 return IntRange::forBoolType();
3480
John McCall862ff872011-07-13 06:35:24 +00003481 // The type of the assignments is the type of the LHS, so the RHS
3482 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003483 case BO_MulAssign:
3484 case BO_DivAssign:
3485 case BO_RemAssign:
3486 case BO_AddAssign:
3487 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003488 case BO_XorAssign:
3489 case BO_OrAssign:
3490 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003491 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003492
John McCall862ff872011-07-13 06:35:24 +00003493 // Simple assignments just pass through the RHS, which will have
3494 // been coerced to the LHS type.
3495 case BO_Assign:
3496 // TODO: bitfields?
3497 return GetExprRange(C, BO->getRHS(), MaxWidth);
3498
John McCallf2370c92010-01-06 05:24:50 +00003499 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003500 case BO_PtrMemD:
3501 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003502 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003503
John McCall60fad452010-01-06 22:07:33 +00003504 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003505 case BO_And:
3506 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003507 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3508 GetExprRange(C, BO->getRHS(), MaxWidth));
3509
John McCallf2370c92010-01-06 05:24:50 +00003510 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003511 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003512 // ...except that we want to treat '1 << (blah)' as logically
3513 // positive. It's an important idiom.
3514 if (IntegerLiteral *I
3515 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3516 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003517 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003518 return IntRange(R.Width, /*NonNegative*/ true);
3519 }
3520 }
3521 // fallthrough
3522
John McCall2de56d12010-08-25 11:45:40 +00003523 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003524 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003525
John McCall60fad452010-01-06 22:07:33 +00003526 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003527 case BO_Shr:
3528 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003529 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3530
3531 // If the shift amount is a positive constant, drop the width by
3532 // that much.
3533 llvm::APSInt shift;
3534 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3535 shift.isNonNegative()) {
3536 unsigned zext = shift.getZExtValue();
3537 if (zext >= L.Width)
3538 L.Width = (L.NonNegative ? 0 : 1);
3539 else
3540 L.Width -= zext;
3541 }
3542
3543 return L;
3544 }
3545
3546 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003547 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003548 return GetExprRange(C, BO->getRHS(), MaxWidth);
3549
John McCall60fad452010-01-06 22:07:33 +00003550 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003551 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003552 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003553 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003554 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003555
John McCall00fe7612011-07-14 22:39:48 +00003556 // The width of a division result is mostly determined by the size
3557 // of the LHS.
3558 case BO_Div: {
3559 // Don't 'pre-truncate' the operands.
3560 unsigned opWidth = C.getIntWidth(E->getType());
3561 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3562
3563 // If the divisor is constant, use that.
3564 llvm::APSInt divisor;
3565 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3566 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3567 if (log2 >= L.Width)
3568 L.Width = (L.NonNegative ? 0 : 1);
3569 else
3570 L.Width = std::min(L.Width - log2, MaxWidth);
3571 return L;
3572 }
3573
3574 // Otherwise, just use the LHS's width.
3575 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3576 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3577 }
3578
3579 // The result of a remainder can't be larger than the result of
3580 // either side.
3581 case BO_Rem: {
3582 // Don't 'pre-truncate' the operands.
3583 unsigned opWidth = C.getIntWidth(E->getType());
3584 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3585 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3586
3587 IntRange meet = IntRange::meet(L, R);
3588 meet.Width = std::min(meet.Width, MaxWidth);
3589 return meet;
3590 }
3591
3592 // The default behavior is okay for these.
3593 case BO_Mul:
3594 case BO_Add:
3595 case BO_Xor:
3596 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003597 break;
3598 }
3599
John McCall00fe7612011-07-14 22:39:48 +00003600 // The default case is to treat the operation as if it were closed
3601 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003602 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3603 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3604 return IntRange::join(L, R);
3605 }
3606
3607 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3608 switch (UO->getOpcode()) {
3609 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003610 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003611 return IntRange::forBoolType();
3612
3613 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003614 case UO_Deref:
3615 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003616 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003617
3618 default:
3619 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3620 }
3621 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003622
3623 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003624 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003625 }
John McCallf2370c92010-01-06 05:24:50 +00003626
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003627 if (FieldDecl *BitField = E->getBitField())
3628 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003629 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003630
John McCall1844a6e2010-11-10 23:38:19 +00003631 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003632}
John McCall51313c32010-01-04 23:31:57 +00003633
Ted Kremenek0692a192012-01-31 05:37:37 +00003634static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003635 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3636}
3637
John McCall51313c32010-01-04 23:31:57 +00003638/// Checks whether the given value, which currently has the given
3639/// source semantics, has the same value when coerced through the
3640/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003641static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3642 const llvm::fltSemantics &Src,
3643 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003644 llvm::APFloat truncated = value;
3645
3646 bool ignored;
3647 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3648 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3649
3650 return truncated.bitwiseIsEqual(value);
3651}
3652
3653/// Checks whether the given value, which currently has the given
3654/// source semantics, has the same value when coerced through the
3655/// target semantics.
3656///
3657/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003658static bool IsSameFloatAfterCast(const APValue &value,
3659 const llvm::fltSemantics &Src,
3660 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003661 if (value.isFloat())
3662 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3663
3664 if (value.isVector()) {
3665 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3666 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3667 return false;
3668 return true;
3669 }
3670
3671 assert(value.isComplexFloat());
3672 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3673 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3674}
3675
Ted Kremenek0692a192012-01-31 05:37:37 +00003676static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003677
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003678static bool IsZero(Sema &S, Expr *E) {
3679 // Suppress cases where we are comparing against an enum constant.
3680 if (const DeclRefExpr *DR =
3681 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3682 if (isa<EnumConstantDecl>(DR->getDecl()))
3683 return false;
3684
3685 // Suppress cases where the '0' value is expanded from a macro.
3686 if (E->getLocStart().isMacroID())
3687 return false;
3688
John McCall323ed742010-05-06 08:58:33 +00003689 llvm::APSInt Value;
3690 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3691}
3692
John McCall372e1032010-10-06 00:25:24 +00003693static bool HasEnumType(Expr *E) {
3694 // Strip off implicit integral promotions.
3695 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003696 if (ICE->getCastKind() != CK_IntegralCast &&
3697 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003698 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003699 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003700 }
3701
3702 return E->getType()->isEnumeralType();
3703}
3704
Ted Kremenek0692a192012-01-31 05:37:37 +00003705static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003706 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003707 if (E->isValueDependent())
3708 return;
3709
John McCall2de56d12010-08-25 11:45:40 +00003710 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003711 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003712 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003713 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003714 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003715 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003716 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003717 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003718 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003719 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003720 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003721 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003722 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003723 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003724 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003725 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3726 }
3727}
3728
3729/// Analyze the operands of the given comparison. Implements the
3730/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003731static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003732 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3733 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003734}
John McCall51313c32010-01-04 23:31:57 +00003735
John McCallba26e582010-01-04 23:21:16 +00003736/// \brief Implements -Wsign-compare.
3737///
Richard Trieudd225092011-09-15 21:56:47 +00003738/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003739static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003740 // The type the comparison is being performed in.
3741 QualType T = E->getLHS()->getType();
3742 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3743 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003744
John McCall323ed742010-05-06 08:58:33 +00003745 // We don't do anything special if this isn't an unsigned integral
3746 // comparison: we're only interested in integral comparisons, and
3747 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003748 //
3749 // We also don't care about value-dependent expressions or expressions
3750 // whose result is a constant.
3751 if (!T->hasUnsignedIntegerRepresentation()
3752 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003753 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003754
Richard Trieudd225092011-09-15 21:56:47 +00003755 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3756 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003757
John McCall323ed742010-05-06 08:58:33 +00003758 // Check to see if one of the (unmodified) operands is of different
3759 // signedness.
3760 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003761 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3762 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003763 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003764 signedOperand = LHS;
3765 unsignedOperand = RHS;
3766 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3767 signedOperand = RHS;
3768 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003769 } else {
John McCall323ed742010-05-06 08:58:33 +00003770 CheckTrivialUnsignedComparison(S, E);
3771 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003772 }
3773
John McCall323ed742010-05-06 08:58:33 +00003774 // Otherwise, calculate the effective range of the signed operand.
3775 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003776
John McCall323ed742010-05-06 08:58:33 +00003777 // Go ahead and analyze implicit conversions in the operands. Note
3778 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003779 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3780 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003781
John McCall323ed742010-05-06 08:58:33 +00003782 // If the signed range is non-negative, -Wsign-compare won't fire,
3783 // but we should still check for comparisons which are always true
3784 // or false.
3785 if (signedRange.NonNegative)
3786 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003787
3788 // For (in)equality comparisons, if the unsigned operand is a
3789 // constant which cannot collide with a overflowed signed operand,
3790 // then reinterpreting the signed operand as unsigned will not
3791 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003792 if (E->isEqualityOp()) {
3793 unsigned comparisonWidth = S.Context.getIntWidth(T);
3794 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003795
John McCall323ed742010-05-06 08:58:33 +00003796 // We should never be unable to prove that the unsigned operand is
3797 // non-negative.
3798 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3799
3800 if (unsignedRange.Width < comparisonWidth)
3801 return;
3802 }
3803
3804 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003805 << LHS->getType() << RHS->getType()
3806 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003807}
3808
John McCall15d7d122010-11-11 03:21:53 +00003809/// Analyzes an attempt to assign the given value to a bitfield.
3810///
3811/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003812static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3813 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003814 assert(Bitfield->isBitField());
3815 if (Bitfield->isInvalidDecl())
3816 return false;
3817
John McCall91b60142010-11-11 05:33:51 +00003818 // White-list bool bitfields.
3819 if (Bitfield->getType()->isBooleanType())
3820 return false;
3821
Douglas Gregor46ff3032011-02-04 13:09:01 +00003822 // Ignore value- or type-dependent expressions.
3823 if (Bitfield->getBitWidth()->isValueDependent() ||
3824 Bitfield->getBitWidth()->isTypeDependent() ||
3825 Init->isValueDependent() ||
3826 Init->isTypeDependent())
3827 return false;
3828
John McCall15d7d122010-11-11 03:21:53 +00003829 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3830
Richard Smith80d4b552011-12-28 19:48:30 +00003831 llvm::APSInt Value;
3832 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003833 return false;
3834
John McCall15d7d122010-11-11 03:21:53 +00003835 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003836 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003837
3838 if (OriginalWidth <= FieldWidth)
3839 return false;
3840
Eli Friedman3a643af2012-01-26 23:11:39 +00003841 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003842 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003843 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003844
Eli Friedman3a643af2012-01-26 23:11:39 +00003845 // Check whether the stored value is equal to the original value.
3846 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003847 if (Value == TruncatedValue)
3848 return false;
3849
Eli Friedman3a643af2012-01-26 23:11:39 +00003850 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00003851 // therefore don't strictly fit into a signed bitfield of width 1.
3852 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00003853 return false;
3854
John McCall15d7d122010-11-11 03:21:53 +00003855 std::string PrettyValue = Value.toString(10);
3856 std::string PrettyTrunc = TruncatedValue.toString(10);
3857
3858 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3859 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3860 << Init->getSourceRange();
3861
3862 return true;
3863}
3864
John McCallbeb22aa2010-11-09 23:24:47 +00003865/// Analyze the given simple or compound assignment for warning-worthy
3866/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00003867static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00003868 // Just recurse on the LHS.
3869 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3870
3871 // We want to recurse on the RHS as normal unless we're assigning to
3872 // a bitfield.
3873 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003874 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3875 E->getOperatorLoc())) {
3876 // Recurse, ignoring any implicit conversions on the RHS.
3877 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3878 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003879 }
3880 }
3881
3882 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3883}
3884
John McCall51313c32010-01-04 23:31:57 +00003885/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003886static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003887 SourceLocation CContext, unsigned diag,
3888 bool pruneControlFlow = false) {
3889 if (pruneControlFlow) {
3890 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3891 S.PDiag(diag)
3892 << SourceType << T << E->getSourceRange()
3893 << SourceRange(CContext));
3894 return;
3895 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003896 S.Diag(E->getExprLoc(), diag)
3897 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3898}
3899
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003900/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003901static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003902 SourceLocation CContext, unsigned diag,
3903 bool pruneControlFlow = false) {
3904 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003905}
3906
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003907/// Diagnose an implicit cast from a literal expression. Does not warn when the
3908/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003909void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3910 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003911 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003912 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003913 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003914 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3915 T->hasUnsignedIntegerRepresentation());
3916 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003917 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003918 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003919 return;
3920
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003921 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3922 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003923}
3924
John McCall091f23f2010-11-09 22:22:12 +00003925std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3926 if (!Range.Width) return "0";
3927
3928 llvm::APSInt ValueInRange = Value;
3929 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003930 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003931 return ValueInRange.toString(10);
3932}
3933
John McCall323ed742010-05-06 08:58:33 +00003934void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003935 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003936 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003937
John McCall323ed742010-05-06 08:58:33 +00003938 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3939 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3940 if (Source == Target) return;
3941 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003942
Chandler Carruth108f7562011-07-26 05:40:03 +00003943 // If the conversion context location is invalid don't complain. We also
3944 // don't want to emit a warning if the issue occurs from the expansion of
3945 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3946 // delay this check as long as possible. Once we detect we are in that
3947 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003948 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003949 return;
3950
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003951 // Diagnose implicit casts to bool.
3952 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3953 if (isa<StringLiteral>(E))
3954 // Warn on string literal to bool. Checks for string literals in logical
3955 // expressions, for instances, assert(0 && "error here"), is prevented
3956 // by a check in AnalyzeImplicitConversions().
3957 return DiagnoseImpCast(S, E, T, CC,
3958 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003959 if (Source->isFunctionType()) {
3960 // Warn on function to bool. Checks free functions and static member
3961 // functions. Weakly imported functions are excluded from the check,
3962 // since it's common to test their value to check whether the linker
3963 // found a definition for them.
3964 ValueDecl *D = 0;
3965 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3966 D = R->getDecl();
3967 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3968 D = M->getMemberDecl();
3969 }
3970
3971 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003972 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3973 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3974 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003975 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3976 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3977 QualType ReturnType;
3978 UnresolvedSet<4> NonTemplateOverloads;
3979 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3980 if (!ReturnType.isNull()
3981 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3982 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3983 << FixItHint::CreateInsertion(
3984 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003985 return;
3986 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003987 }
3988 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003989 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003990 }
John McCall51313c32010-01-04 23:31:57 +00003991
3992 // Strip vector types.
3993 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003994 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003995 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003996 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003997 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003998 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003999
4000 // If the vector cast is cast between two vectors of the same size, it is
4001 // a bitcast, not a conversion.
4002 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4003 return;
John McCall51313c32010-01-04 23:31:57 +00004004
4005 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4006 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4007 }
4008
4009 // Strip complex types.
4010 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004011 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004012 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004013 return;
4014
John McCallb4eb64d2010-10-08 02:01:28 +00004015 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004016 }
John McCall51313c32010-01-04 23:31:57 +00004017
4018 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4019 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4020 }
4021
4022 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4023 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4024
4025 // If the source is floating point...
4026 if (SourceBT && SourceBT->isFloatingPoint()) {
4027 // ...and the target is floating point...
4028 if (TargetBT && TargetBT->isFloatingPoint()) {
4029 // ...then warn if we're dropping FP rank.
4030
4031 // Builtin FP kinds are ordered by increasing FP rank.
4032 if (SourceBT->getKind() > TargetBT->getKind()) {
4033 // Don't warn about float constants that are precisely
4034 // representable in the target type.
4035 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004036 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004037 // Value might be a float, a float vector, or a float complex.
4038 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004039 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4040 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004041 return;
4042 }
4043
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004044 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004045 return;
4046
John McCallb4eb64d2010-10-08 02:01:28 +00004047 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004048 }
4049 return;
4050 }
4051
Ted Kremenekef9ff882011-03-10 20:03:42 +00004052 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00004053 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004054 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004055 return;
4056
Chandler Carrutha5b93322011-02-17 11:05:49 +00004057 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004058 // We also want to warn on, e.g., "int i = -1.234"
4059 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4060 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4061 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4062
Chandler Carruthf65076e2011-04-10 08:36:24 +00004063 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4064 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004065 } else {
4066 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4067 }
4068 }
John McCall51313c32010-01-04 23:31:57 +00004069
4070 return;
4071 }
4072
John McCallf2370c92010-01-06 05:24:50 +00004073 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004074 return;
4075
Richard Trieu1838ca52011-05-29 19:59:02 +00004076 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4077 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004078 SourceLocation Loc = E->getSourceRange().getBegin();
4079 if (Loc.isMacroID())
4080 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4081 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4082 << T << Loc << clang::SourceRange(CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00004083 return;
4084 }
4085
John McCall323ed742010-05-06 08:58:33 +00004086 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004087 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004088
4089 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004090 // If the source is a constant, use a default-on diagnostic.
4091 // TODO: this should happen for bitfield stores, too.
4092 llvm::APSInt Value(32);
4093 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004094 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004095 return;
4096
John McCall091f23f2010-11-09 22:22:12 +00004097 std::string PrettySourceValue = Value.toString(10);
4098 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4099
Ted Kremenek5e745da2011-10-22 02:37:33 +00004100 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4101 S.PDiag(diag::warn_impcast_integer_precision_constant)
4102 << PrettySourceValue << PrettyTargetValue
4103 << E->getType() << T << E->getSourceRange()
4104 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004105 return;
4106 }
4107
Chris Lattnerb792b302011-06-14 04:51:15 +00004108 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004109 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004110 return;
4111
John McCallf2370c92010-01-06 05:24:50 +00004112 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004113 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4114 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004115 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004116 }
4117
4118 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4119 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4120 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004121
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004122 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004123 return;
4124
John McCall323ed742010-05-06 08:58:33 +00004125 unsigned DiagID = diag::warn_impcast_integer_sign;
4126
4127 // Traditionally, gcc has warned about this under -Wsign-compare.
4128 // We also want to warn about it in -Wconversion.
4129 // So if -Wconversion is off, use a completely identical diagnostic
4130 // in the sign-compare group.
4131 // The conditional-checking code will
4132 if (ICContext) {
4133 DiagID = diag::warn_impcast_integer_sign_conditional;
4134 *ICContext = true;
4135 }
4136
John McCallb4eb64d2010-10-08 02:01:28 +00004137 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004138 }
4139
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004140 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004141 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4142 // type, to give us better diagnostics.
4143 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004144 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004145 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4146 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4147 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4148 SourceType = S.Context.getTypeDeclType(Enum);
4149 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4150 }
4151 }
4152
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004153 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4154 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4155 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004156 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004157 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004158 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004159 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004160 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004161 return;
4162
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004163 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004164 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004165 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004166
John McCall51313c32010-01-04 23:31:57 +00004167 return;
4168}
4169
John McCall323ed742010-05-06 08:58:33 +00004170void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4171
4172void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004173 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004174 E = E->IgnoreParenImpCasts();
4175
4176 if (isa<ConditionalOperator>(E))
4177 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4178
John McCallb4eb64d2010-10-08 02:01:28 +00004179 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004180 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004181 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004182 return;
4183}
4184
4185void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004186 SourceLocation CC = E->getQuestionLoc();
4187
4188 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004189
4190 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004191 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4192 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004193
4194 // If -Wconversion would have warned about either of the candidates
4195 // for a signedness conversion to the context type...
4196 if (!Suspicious) return;
4197
4198 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004199 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4200 CC))
John McCall323ed742010-05-06 08:58:33 +00004201 return;
4202
John McCall323ed742010-05-06 08:58:33 +00004203 // ...then check whether it would have warned about either of the
4204 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004205 if (E->getType() == T) return;
4206
4207 Suspicious = false;
4208 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4209 E->getType(), CC, &Suspicious);
4210 if (!Suspicious)
4211 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004212 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004213}
4214
4215/// AnalyzeImplicitConversions - Find and report any interesting
4216/// implicit conversions in the given expression. There are a couple
4217/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004218void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004219 QualType T = OrigE->getType();
4220 Expr *E = OrigE->IgnoreParenImpCasts();
4221
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004222 if (E->isTypeDependent() || E->isValueDependent())
4223 return;
4224
John McCall323ed742010-05-06 08:58:33 +00004225 // For conditional operators, we analyze the arguments as if they
4226 // were being fed directly into the output.
4227 if (isa<ConditionalOperator>(E)) {
4228 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4229 CheckConditionalOperator(S, CO, T);
4230 return;
4231 }
4232
4233 // Go ahead and check any implicit conversions we might have skipped.
4234 // The non-canonical typecheck is just an optimization;
4235 // CheckImplicitConversion will filter out dead implicit conversions.
4236 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004237 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004238
4239 // Now continue drilling into this expression.
4240
4241 // Skip past explicit casts.
4242 if (isa<ExplicitCastExpr>(E)) {
4243 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004244 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004245 }
4246
John McCallbeb22aa2010-11-09 23:24:47 +00004247 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4248 // Do a somewhat different check with comparison operators.
4249 if (BO->isComparisonOp())
4250 return AnalyzeComparison(S, BO);
4251
Eli Friedman0fa06382012-01-26 23:34:06 +00004252 // And with simple assignments.
4253 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004254 return AnalyzeAssignment(S, BO);
4255 }
John McCall323ed742010-05-06 08:58:33 +00004256
4257 // These break the otherwise-useful invariant below. Fortunately,
4258 // we don't really need to recurse into them, because any internal
4259 // expressions should have been analyzed already when they were
4260 // built into statements.
4261 if (isa<StmtExpr>(E)) return;
4262
4263 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004264 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004265
4266 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004267 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004268 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4269 bool IsLogicalOperator = BO && BO->isLogicalOp();
4270 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004271 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004272 if (!ChildExpr)
4273 continue;
4274
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004275 if (IsLogicalOperator &&
4276 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4277 // Ignore checking string literals that are in logical operators.
4278 continue;
4279 AnalyzeImplicitConversions(S, ChildExpr, CC);
4280 }
John McCall323ed742010-05-06 08:58:33 +00004281}
4282
4283} // end anonymous namespace
4284
4285/// Diagnoses "dangerous" implicit conversions within the given
4286/// expression (which is a full expression). Implements -Wconversion
4287/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004288///
4289/// \param CC the "context" location of the implicit conversion, i.e.
4290/// the most location of the syntactic entity requiring the implicit
4291/// conversion
4292void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004293 // Don't diagnose in unevaluated contexts.
4294 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4295 return;
4296
4297 // Don't diagnose for value- or type-dependent expressions.
4298 if (E->isTypeDependent() || E->isValueDependent())
4299 return;
4300
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004301 // Check for array bounds violations in cases where the check isn't triggered
4302 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4303 // ArraySubscriptExpr is on the RHS of a variable initialization.
4304 CheckArrayAccess(E);
4305
John McCallb4eb64d2010-10-08 02:01:28 +00004306 // This is not the right CC for (e.g.) a variable initialization.
4307 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004308}
4309
John McCall15d7d122010-11-11 03:21:53 +00004310void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4311 FieldDecl *BitField,
4312 Expr *Init) {
4313 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4314}
4315
Mike Stumpf8c49212010-01-21 03:59:47 +00004316/// CheckParmsForFunctionDef - Check that the parameters of the given
4317/// function are appropriate for the definition of a function. This
4318/// takes care of any checks that cannot be performed on the
4319/// declaration itself, e.g., that the types of each of the function
4320/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004321bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4322 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004323 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004324 for (; P != PEnd; ++P) {
4325 ParmVarDecl *Param = *P;
4326
Mike Stumpf8c49212010-01-21 03:59:47 +00004327 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4328 // function declarator that is part of a function definition of
4329 // that function shall not have incomplete type.
4330 //
4331 // This is also C++ [dcl.fct]p6.
4332 if (!Param->isInvalidDecl() &&
4333 RequireCompleteType(Param->getLocation(), Param->getType(),
4334 diag::err_typecheck_decl_incomplete_type)) {
4335 Param->setInvalidDecl();
4336 HasInvalidParm = true;
4337 }
4338
4339 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4340 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004341 if (CheckParameterNames &&
4342 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004343 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004344 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004345 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004346
4347 // C99 6.7.5.3p12:
4348 // If the function declarator is not part of a definition of that
4349 // function, parameters may have incomplete type and may use the [*]
4350 // notation in their sequences of declarator specifiers to specify
4351 // variable length array types.
4352 QualType PType = Param->getOriginalType();
4353 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4354 if (AT->getSizeModifier() == ArrayType::Star) {
4355 // FIXME: This diagnosic should point the the '[*]' if source-location
4356 // information is added for it.
4357 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4358 }
4359 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004360 }
4361
4362 return HasInvalidParm;
4363}
John McCallb7f4ffe2010-08-12 21:44:57 +00004364
4365/// CheckCastAlign - Implements -Wcast-align, which warns when a
4366/// pointer cast increases the alignment requirements.
4367void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4368 // This is actually a lot of work to potentially be doing on every
4369 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004370 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4371 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004372 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004373 return;
4374
4375 // Ignore dependent types.
4376 if (T->isDependentType() || Op->getType()->isDependentType())
4377 return;
4378
4379 // Require that the destination be a pointer type.
4380 const PointerType *DestPtr = T->getAs<PointerType>();
4381 if (!DestPtr) return;
4382
4383 // If the destination has alignment 1, we're done.
4384 QualType DestPointee = DestPtr->getPointeeType();
4385 if (DestPointee->isIncompleteType()) return;
4386 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4387 if (DestAlign.isOne()) return;
4388
4389 // Require that the source be a pointer type.
4390 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4391 if (!SrcPtr) return;
4392 QualType SrcPointee = SrcPtr->getPointeeType();
4393
4394 // Whitelist casts from cv void*. We already implicitly
4395 // whitelisted casts to cv void*, since they have alignment 1.
4396 // Also whitelist casts involving incomplete types, which implicitly
4397 // includes 'void'.
4398 if (SrcPointee->isIncompleteType()) return;
4399
4400 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4401 if (SrcAlign >= DestAlign) return;
4402
4403 Diag(TRange.getBegin(), diag::warn_cast_align)
4404 << Op->getType() << T
4405 << static_cast<unsigned>(SrcAlign.getQuantity())
4406 << static_cast<unsigned>(DestAlign.getQuantity())
4407 << TRange << Op->getSourceRange();
4408}
4409
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004410static const Type* getElementType(const Expr *BaseExpr) {
4411 const Type* EltType = BaseExpr->getType().getTypePtr();
4412 if (EltType->isAnyPointerType())
4413 return EltType->getPointeeType().getTypePtr();
4414 else if (EltType->isArrayType())
4415 return EltType->getBaseElementTypeUnsafe();
4416 return EltType;
4417}
4418
Chandler Carruthc2684342011-08-05 09:10:50 +00004419/// \brief Check whether this array fits the idiom of a size-one tail padded
4420/// array member of a struct.
4421///
4422/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4423/// commonly used to emulate flexible arrays in C89 code.
4424static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4425 const NamedDecl *ND) {
4426 if (Size != 1 || !ND) return false;
4427
4428 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4429 if (!FD) return false;
4430
4431 // Don't consider sizes resulting from macro expansions or template argument
4432 // substitution to form C89 tail-padded arrays.
4433 ConstantArrayTypeLoc TL =
4434 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4435 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4436 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4437 return false;
4438
4439 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004440 if (!RD) return false;
4441 if (RD->isUnion()) return false;
4442 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4443 if (!CRD->isStandardLayout()) return false;
4444 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004445
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004446 // See if this is the last field decl in the record.
4447 const Decl *D = FD;
4448 while ((D = D->getNextDeclInContext()))
4449 if (isa<FieldDecl>(D))
4450 return false;
4451 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004452}
4453
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004454void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004455 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004456 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004457 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004458 if (IndexExpr->isValueDependent())
4459 return;
4460
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004461 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004462 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004463 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004464 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004465 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004466 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004467
Chandler Carruth34064582011-02-17 20:55:08 +00004468 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004469 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004470 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004471 if (IndexNegated)
4472 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004473
Chandler Carruthba447122011-08-05 08:07:29 +00004474 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004475 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4476 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004477 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004478 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004479
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004480 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004481 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004482 if (!size.isStrictlyPositive())
4483 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004484
4485 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004486 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004487 // Make sure we're comparing apples to apples when comparing index to size
4488 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4489 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004490 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004491 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004492 if (ptrarith_typesize != array_typesize) {
4493 // There's a cast to a different size type involved
4494 uint64_t ratio = array_typesize / ptrarith_typesize;
4495 // TODO: Be smarter about handling cases where array_typesize is not a
4496 // multiple of ptrarith_typesize
4497 if (ptrarith_typesize * ratio == array_typesize)
4498 size *= llvm::APInt(size.getBitWidth(), ratio);
4499 }
4500 }
4501
Chandler Carruth34064582011-02-17 20:55:08 +00004502 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004503 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004504 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004505 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004506
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004507 // For array subscripting the index must be less than size, but for pointer
4508 // arithmetic also allow the index (offset) to be equal to size since
4509 // computing the next address after the end of the array is legal and
4510 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004511 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004512 return;
4513
4514 // Also don't warn for arrays of size 1 which are members of some
4515 // structure. These are often used to approximate flexible arrays in C89
4516 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004517 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004518 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004519
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004520 // Suppress the warning if the subscript expression (as identified by the
4521 // ']' location) and the index expression are both from macro expansions
4522 // within a system header.
4523 if (ASE) {
4524 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4525 ASE->getRBracketLoc());
4526 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4527 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4528 IndexExpr->getLocStart());
4529 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4530 return;
4531 }
4532 }
4533
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004534 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004535 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004536 DiagID = diag::warn_array_index_exceeds_bounds;
4537
4538 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4539 PDiag(DiagID) << index.toString(10, true)
4540 << size.toString(10, true)
4541 << (unsigned)size.getLimitedValue(~0U)
4542 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004543 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004544 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004545 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004546 DiagID = diag::warn_ptr_arith_precedes_bounds;
4547 if (index.isNegative()) index = -index;
4548 }
4549
4550 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4551 PDiag(DiagID) << index.toString(10, true)
4552 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004553 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004554
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004555 if (!ND) {
4556 // Try harder to find a NamedDecl to point at in the note.
4557 while (const ArraySubscriptExpr *ASE =
4558 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4559 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4560 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4561 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4562 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4563 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4564 }
4565
Chandler Carruth35001ca2011-02-17 21:10:52 +00004566 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004567 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4568 PDiag(diag::note_array_index_out_of_bounds)
4569 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004570}
4571
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004572void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004573 int AllowOnePastEnd = 0;
4574 while (expr) {
4575 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004576 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004577 case Stmt::ArraySubscriptExprClass: {
4578 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004579 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004580 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004581 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004582 }
4583 case Stmt::UnaryOperatorClass: {
4584 // Only unwrap the * and & unary operators
4585 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4586 expr = UO->getSubExpr();
4587 switch (UO->getOpcode()) {
4588 case UO_AddrOf:
4589 AllowOnePastEnd++;
4590 break;
4591 case UO_Deref:
4592 AllowOnePastEnd--;
4593 break;
4594 default:
4595 return;
4596 }
4597 break;
4598 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004599 case Stmt::ConditionalOperatorClass: {
4600 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4601 if (const Expr *lhs = cond->getLHS())
4602 CheckArrayAccess(lhs);
4603 if (const Expr *rhs = cond->getRHS())
4604 CheckArrayAccess(rhs);
4605 return;
4606 }
4607 default:
4608 return;
4609 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004610 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004611}
John McCallf85e1932011-06-15 23:02:42 +00004612
4613//===--- CHECK: Objective-C retain cycles ----------------------------------//
4614
4615namespace {
4616 struct RetainCycleOwner {
4617 RetainCycleOwner() : Variable(0), Indirect(false) {}
4618 VarDecl *Variable;
4619 SourceRange Range;
4620 SourceLocation Loc;
4621 bool Indirect;
4622
4623 void setLocsFrom(Expr *e) {
4624 Loc = e->getExprLoc();
4625 Range = e->getSourceRange();
4626 }
4627 };
4628}
4629
4630/// Consider whether capturing the given variable can possibly lead to
4631/// a retain cycle.
4632static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4633 // In ARC, it's captured strongly iff the variable has __strong
4634 // lifetime. In MRR, it's captured strongly if the variable is
4635 // __block and has an appropriate type.
4636 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4637 return false;
4638
4639 owner.Variable = var;
4640 owner.setLocsFrom(ref);
4641 return true;
4642}
4643
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004644static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004645 while (true) {
4646 e = e->IgnoreParens();
4647 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4648 switch (cast->getCastKind()) {
4649 case CK_BitCast:
4650 case CK_LValueBitCast:
4651 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004652 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004653 e = cast->getSubExpr();
4654 continue;
4655
John McCallf85e1932011-06-15 23:02:42 +00004656 default:
4657 return false;
4658 }
4659 }
4660
4661 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4662 ObjCIvarDecl *ivar = ref->getDecl();
4663 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4664 return false;
4665
4666 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004667 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004668 return false;
4669
4670 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4671 owner.Indirect = true;
4672 return true;
4673 }
4674
4675 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4676 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4677 if (!var) return false;
4678 return considerVariable(var, ref, owner);
4679 }
4680
John McCallf85e1932011-06-15 23:02:42 +00004681 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4682 if (member->isArrow()) return false;
4683
4684 // Don't count this as an indirect ownership.
4685 e = member->getBase();
4686 continue;
4687 }
4688
John McCall4b9c2d22011-11-06 09:01:30 +00004689 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4690 // Only pay attention to pseudo-objects on property references.
4691 ObjCPropertyRefExpr *pre
4692 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4693 ->IgnoreParens());
4694 if (!pre) return false;
4695 if (pre->isImplicitProperty()) return false;
4696 ObjCPropertyDecl *property = pre->getExplicitProperty();
4697 if (!property->isRetaining() &&
4698 !(property->getPropertyIvarDecl() &&
4699 property->getPropertyIvarDecl()->getType()
4700 .getObjCLifetime() == Qualifiers::OCL_Strong))
4701 return false;
4702
4703 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004704 if (pre->isSuperReceiver()) {
4705 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4706 if (!owner.Variable)
4707 return false;
4708 owner.Loc = pre->getLocation();
4709 owner.Range = pre->getSourceRange();
4710 return true;
4711 }
John McCall4b9c2d22011-11-06 09:01:30 +00004712 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4713 ->getSourceExpr());
4714 continue;
4715 }
4716
John McCallf85e1932011-06-15 23:02:42 +00004717 // Array ivars?
4718
4719 return false;
4720 }
4721}
4722
4723namespace {
4724 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4725 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4726 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4727 Variable(variable), Capturer(0) {}
4728
4729 VarDecl *Variable;
4730 Expr *Capturer;
4731
4732 void VisitDeclRefExpr(DeclRefExpr *ref) {
4733 if (ref->getDecl() == Variable && !Capturer)
4734 Capturer = ref;
4735 }
4736
John McCallf85e1932011-06-15 23:02:42 +00004737 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4738 if (Capturer) return;
4739 Visit(ref->getBase());
4740 if (Capturer && ref->isFreeIvar())
4741 Capturer = ref;
4742 }
4743
4744 void VisitBlockExpr(BlockExpr *block) {
4745 // Look inside nested blocks
4746 if (block->getBlockDecl()->capturesVariable(Variable))
4747 Visit(block->getBlockDecl()->getBody());
4748 }
4749 };
4750}
4751
4752/// Check whether the given argument is a block which captures a
4753/// variable.
4754static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4755 assert(owner.Variable && owner.Loc.isValid());
4756
4757 e = e->IgnoreParenCasts();
4758 BlockExpr *block = dyn_cast<BlockExpr>(e);
4759 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4760 return 0;
4761
4762 FindCaptureVisitor visitor(S.Context, owner.Variable);
4763 visitor.Visit(block->getBlockDecl()->getBody());
4764 return visitor.Capturer;
4765}
4766
4767static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4768 RetainCycleOwner &owner) {
4769 assert(capturer);
4770 assert(owner.Variable && owner.Loc.isValid());
4771
4772 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4773 << owner.Variable << capturer->getSourceRange();
4774 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4775 << owner.Indirect << owner.Range;
4776}
4777
4778/// Check for a keyword selector that starts with the word 'add' or
4779/// 'set'.
4780static bool isSetterLikeSelector(Selector sel) {
4781 if (sel.isUnarySelector()) return false;
4782
Chris Lattner5f9e2722011-07-23 10:55:15 +00004783 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004784 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004785 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004786 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004787 else if (str.startswith("add")) {
4788 // Specially whitelist 'addOperationWithBlock:'.
4789 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4790 return false;
4791 str = str.substr(3);
4792 }
John McCallf85e1932011-06-15 23:02:42 +00004793 else
4794 return false;
4795
4796 if (str.empty()) return true;
4797 return !islower(str.front());
4798}
4799
4800/// Check a message send to see if it's likely to cause a retain cycle.
4801void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4802 // Only check instance methods whose selector looks like a setter.
4803 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4804 return;
4805
4806 // Try to find a variable that the receiver is strongly owned by.
4807 RetainCycleOwner owner;
4808 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004809 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004810 return;
4811 } else {
4812 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4813 owner.Variable = getCurMethodDecl()->getSelfDecl();
4814 owner.Loc = msg->getSuperLoc();
4815 owner.Range = msg->getSuperLoc();
4816 }
4817
4818 // Check whether the receiver is captured by any of the arguments.
4819 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4820 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4821 return diagnoseRetainCycle(*this, capturer, owner);
4822}
4823
4824/// Check a property assign to see if it's likely to cause a retain cycle.
4825void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4826 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004827 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004828 return;
4829
4830 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4831 diagnoseRetainCycle(*this, capturer, owner);
4832}
4833
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004834bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004835 QualType LHS, Expr *RHS) {
4836 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4837 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004838 return false;
4839 // strip off any implicit cast added to get to the one arc-specific
4840 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004841 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004842 Diag(Loc, diag::warn_arc_retained_assign)
4843 << (LT == Qualifiers::OCL_ExplicitNone)
4844 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004845 return true;
4846 }
4847 RHS = cast->getSubExpr();
4848 }
4849 return false;
John McCallf85e1932011-06-15 23:02:42 +00004850}
4851
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004852void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4853 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004854 QualType LHSType;
4855 // PropertyRef on LHS type need be directly obtained from
4856 // its declaration as it has a PsuedoType.
4857 ObjCPropertyRefExpr *PRE
4858 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4859 if (PRE && !PRE->isImplicitProperty()) {
4860 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4861 if (PD)
4862 LHSType = PD->getType();
4863 }
4864
4865 if (LHSType.isNull())
4866 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004867 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4868 return;
4869 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4870 // FIXME. Check for other life times.
4871 if (LT != Qualifiers::OCL_None)
4872 return;
4873
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004874 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004875 if (PRE->isImplicitProperty())
4876 return;
4877 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4878 if (!PD)
4879 return;
4880
4881 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004882 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4883 // when 'assign' attribute was not explicitly specified
4884 // by user, ignore it and rely on property type itself
4885 // for lifetime info.
4886 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4887 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4888 LHSType->isObjCRetainableType())
4889 return;
4890
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004891 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004892 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004893 Diag(Loc, diag::warn_arc_retained_property_assign)
4894 << RHS->getSourceRange();
4895 return;
4896 }
4897 RHS = cast->getSubExpr();
4898 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004899 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004900 }
4901}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00004902
4903//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
4904
4905namespace {
4906bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
4907 SourceLocation StmtLoc,
4908 const NullStmt *Body) {
4909 // Do not warn if the body is a macro that expands to nothing, e.g:
4910 //
4911 // #define CALL(x)
4912 // if (condition)
4913 // CALL(0);
4914 //
4915 if (Body->hasLeadingEmptyMacro())
4916 return false;
4917
4918 // Get line numbers of statement and body.
4919 bool StmtLineInvalid;
4920 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
4921 &StmtLineInvalid);
4922 if (StmtLineInvalid)
4923 return false;
4924
4925 bool BodyLineInvalid;
4926 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
4927 &BodyLineInvalid);
4928 if (BodyLineInvalid)
4929 return false;
4930
4931 // Warn if null statement and body are on the same line.
4932 if (StmtLine != BodyLine)
4933 return false;
4934
4935 return true;
4936}
4937} // Unnamed namespace
4938
4939void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4940 const Stmt *Body,
4941 unsigned DiagID) {
4942 // Since this is a syntactic check, don't emit diagnostic for template
4943 // instantiations, this just adds noise.
4944 if (CurrentInstantiationScope)
4945 return;
4946
4947 // The body should be a null statement.
4948 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4949 if (!NBody)
4950 return;
4951
4952 // Do the usual checks.
4953 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4954 return;
4955
4956 Diag(NBody->getSemiLoc(), DiagID);
4957 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4958}
4959
4960void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
4961 const Stmt *PossibleBody) {
4962 assert(!CurrentInstantiationScope); // Ensured by caller
4963
4964 SourceLocation StmtLoc;
4965 const Stmt *Body;
4966 unsigned DiagID;
4967 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
4968 StmtLoc = FS->getRParenLoc();
4969 Body = FS->getBody();
4970 DiagID = diag::warn_empty_for_body;
4971 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
4972 StmtLoc = WS->getCond()->getSourceRange().getEnd();
4973 Body = WS->getBody();
4974 DiagID = diag::warn_empty_while_body;
4975 } else
4976 return; // Neither `for' nor `while'.
4977
4978 // The body should be a null statement.
4979 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4980 if (!NBody)
4981 return;
4982
4983 // Skip expensive checks if diagnostic is disabled.
4984 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
4985 DiagnosticsEngine::Ignored)
4986 return;
4987
4988 // Do the usual checks.
4989 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4990 return;
4991
4992 // `for(...);' and `while(...);' are popular idioms, so in order to keep
4993 // noise level low, emit diagnostics only if for/while is followed by a
4994 // CompoundStmt, e.g.:
4995 // for (int i = 0; i < n; i++);
4996 // {
4997 // a(i);
4998 // }
4999 // or if for/while is followed by a statement with more indentation
5000 // than for/while itself:
5001 // for (int i = 0; i < n; i++);
5002 // a(i);
5003 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5004 if (!ProbableTypo) {
5005 bool BodyColInvalid;
5006 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5007 PossibleBody->getLocStart(),
5008 &BodyColInvalid);
5009 if (BodyColInvalid)
5010 return;
5011
5012 bool StmtColInvalid;
5013 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5014 S->getLocStart(),
5015 &StmtColInvalid);
5016 if (StmtColInvalid)
5017 return;
5018
5019 if (BodyCol > StmtCol)
5020 ProbableTypo = true;
5021 }
5022
5023 if (ProbableTypo) {
5024 Diag(NBody->getSemiLoc(), DiagID);
5025 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5026 }
5027}