blob: ef7dc8819f8194d4e0e4e791a0762bb512934475 [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"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000269 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
273 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000290 default:
291 break;
292 }
293 }
294
295 return move(TheCallResult);
296}
297
Nate Begeman61eecf52010-06-14 05:21:25 +0000298// Get the valid immediate range for the specified NEON type code.
299static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000300 NeonTypeFlags Type(t);
301 int IsQuad = Type.isQuad();
302 switch (Type.getEltType()) {
303 case NeonTypeFlags::Int8:
304 case NeonTypeFlags::Poly8:
305 return shift ? 7 : (8 << IsQuad) - 1;
306 case NeonTypeFlags::Int16:
307 case NeonTypeFlags::Poly16:
308 return shift ? 15 : (4 << IsQuad) - 1;
309 case NeonTypeFlags::Int32:
310 return shift ? 31 : (2 << IsQuad) - 1;
311 case NeonTypeFlags::Int64:
312 return shift ? 63 : (1 << IsQuad) - 1;
313 case NeonTypeFlags::Float16:
314 assert(!shift && "cannot shift float types!");
315 return (4 << IsQuad) - 1;
316 case NeonTypeFlags::Float32:
317 assert(!shift && "cannot shift float types!");
318 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000319 }
David Blaikie7530c032012-01-17 06:56:22 +0000320 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000321}
322
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000323/// getNeonEltType - Return the QualType corresponding to the elements of
324/// the vector type specified by the NeonTypeFlags. This is used to check
325/// the pointer arguments for Neon load/store intrinsics.
326static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
327 switch (Flags.getEltType()) {
328 case NeonTypeFlags::Int8:
329 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
330 case NeonTypeFlags::Int16:
331 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
332 case NeonTypeFlags::Int32:
333 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
334 case NeonTypeFlags::Int64:
335 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
336 case NeonTypeFlags::Poly8:
337 return Context.SignedCharTy;
338 case NeonTypeFlags::Poly16:
339 return Context.ShortTy;
340 case NeonTypeFlags::Float16:
341 return Context.UnsignedShortTy;
342 case NeonTypeFlags::Float32:
343 return Context.FloatTy;
344 }
David Blaikie7530c032012-01-17 06:56:22 +0000345 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000346}
347
Nate Begeman26a31422010-06-08 02:47:44 +0000348bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000349 llvm::APSInt Result;
350
Nate Begeman0d15c532010-06-13 04:47:52 +0000351 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000353 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000354 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000355 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000356#define GET_NEON_OVERLOAD_CHECK
357#include "clang/Basic/arm_neon.inc"
358#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000359 }
360
Nate Begeman0d15c532010-06-13 04:47:52 +0000361 // For NEON intrinsics which are overloaded on vector element type, validate
362 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000363 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000364 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000365 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000366 return true;
367
Bob Wilsonda95f732011-11-08 01:16:11 +0000368 TV = Result.getLimitedValue(64);
369 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000370 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000371 << TheCall->getArg(ImmArg)->getSourceRange();
372 }
373
Bob Wilson46482552011-11-16 21:32:23 +0000374 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000375 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000376 Expr *Arg = TheCall->getArg(PtrArgNum);
377 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
378 Arg = ICE->getSubExpr();
379 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
380 QualType RHSTy = RHS.get()->getType();
381 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
382 if (HasConstPtr)
383 EltTy = EltTy.withConst();
384 QualType LHSTy = Context.getPointerType(EltTy);
385 AssignConvertType ConvTy;
386 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
387 if (RHS.isInvalid())
388 return true;
389 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
390 RHS.get(), AA_Assigning))
391 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000393
Nate Begeman0d15c532010-06-13 04:47:52 +0000394 // For NEON intrinsics which take an immediate value as part of the
395 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000396 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000397 switch (BuiltinID) {
398 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000399 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
400 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000401 case ARM::BI__builtin_arm_vcvtr_f:
402 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000403#define GET_NEON_IMMEDIATE_CHECK
404#include "clang/Basic/arm_neon.inc"
405#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000406 };
407
Nate Begeman61eecf52010-06-14 05:21:25 +0000408 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000409 if (SemaBuiltinConstantArg(TheCall, i, Result))
410 return true;
411
Nate Begeman61eecf52010-06-14 05:21:25 +0000412 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000414 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000415 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000416 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000417
Nate Begeman99c40bb2010-08-03 21:32:34 +0000418 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000419 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000420}
Daniel Dunbarde454282008-10-02 18:44:07 +0000421
Richard Smith831421f2012-06-25 20:30:08 +0000422/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
423/// parameter with the FormatAttr's correct format_idx and firstDataArg.
424/// Returns true when the format fits the function and the FormatStringInfo has
425/// been populated.
426bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
427 FormatStringInfo *FSI) {
428 FSI->HasVAListArg = Format->getFirstArg() == 0;
429 FSI->FormatIdx = Format->getFormatIdx() - 1;
430 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000431
Richard Smith831421f2012-06-25 20:30:08 +0000432 // The way the format attribute works in GCC, the implicit this argument
433 // of member functions is counted. However, it doesn't appear in our own
434 // lists, so decrement format_idx in that case.
435 if (IsCXXMember) {
436 if(FSI->FormatIdx == 0)
437 return false;
438 --FSI->FormatIdx;
439 if (FSI->FirstDataArg != 0)
440 --FSI->FirstDataArg;
441 }
442 return true;
443}
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Richard Smith831421f2012-06-25 20:30:08 +0000445/// Handles the checks for format strings, non-POD arguments to vararg
446/// functions, and NULL arguments passed to non-NULL parameters.
447void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
448 unsigned NumArgs,
449 unsigned NumProtoArgs,
450 bool IsMemberFunction,
451 SourceLocation Loc,
452 SourceRange Range,
453 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000454 // FIXME: This mechanism should be abstracted to be less fragile and
455 // more efficient. For example, just map function ids to custom
456 // handlers.
457
Ted Kremenekc82faca2010-09-09 04:33:05 +0000458 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000459 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000460 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000461 I = FDecl->specific_attr_begin<FormatAttr>(),
462 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
463 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, Loc, Range))
464 HandledFormatString = true;
465
466 // Refuse POD arguments that weren't caught by the format string
467 // checks above.
468 if (!HandledFormatString && CallType != VariadicDoesNotApply)
469 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
470 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Ted Kremenekc82faca2010-09-09 04:33:05 +0000472 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000473 I = FDecl->specific_attr_begin<NonNullAttr>(),
474 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
475 CheckNonNullArguments(*I, Args, Loc);
476}
477
478/// CheckConstructorCall - Check a constructor call for correctness and safety
479/// properties not enforced by the C type system.
480void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
481 unsigned NumArgs,
482 const FunctionProtoType *Proto,
483 SourceLocation Loc) {
484 VariadicCallType CallType =
485 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
486 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
487 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
488}
489
490/// CheckFunctionCall - Check a direct function call for various correctness
491/// and safety properties not strictly enforced by the C type system.
492bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
493 const FunctionProtoType *Proto) {
494 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
495 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
496 TheCall->getCallee());
497 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
498 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
499 IsMemberFunction, TheCall->getRParenLoc(),
500 TheCall->getCallee()->getSourceRange(), CallType);
501
502 IdentifierInfo *FnInfo = FDecl->getIdentifier();
503 // None of the checks below are needed for functions that don't have
504 // simple names (e.g., C++ conversion functions).
505 if (!FnInfo)
506 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000507
Anna Zaks0a151a12012-01-17 00:37:07 +0000508 unsigned CMId = FDecl->getMemoryFunctionKind();
509 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000510 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000511
Anna Zaksd9b859a2012-01-13 21:52:01 +0000512 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000513 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000514 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000515 else if (CMId == Builtin::BIstrncat)
516 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000517 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000518 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000519
Anders Carlssond406bf02009-08-16 01:56:34 +0000520 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000521}
522
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000523bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
524 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000525 VariadicCallType CallType =
526 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000527
Richard Smith831421f2012-06-25 20:30:08 +0000528 checkCall(Method, Args, NumArgs, Method->param_size(),
529 /*IsMemberFunction=*/false,
530 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000531
532 return false;
533}
534
Richard Smith831421f2012-06-25 20:30:08 +0000535bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
536 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000537 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
538 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000539 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000541 QualType Ty = V->getType();
542 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000543 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Richard Smith831421f2012-06-25 20:30:08 +0000545 VariadicCallType CallType =
546 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
547 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000548
Richard Smith831421f2012-06-25 20:30:08 +0000549 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
550 NumProtoArgs, /*IsMemberFunction=*/false,
551 TheCall->getRParenLoc(),
552 TheCall->getCallee()->getSourceRange(), CallType);
553
Anders Carlssond406bf02009-08-16 01:56:34 +0000554 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000555}
556
Richard Smithff34d402012-04-12 05:08:17 +0000557ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
558 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000559 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
560 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000561
Richard Smithff34d402012-04-12 05:08:17 +0000562 // All these operations take one of the following forms:
563 enum {
564 // C __c11_atomic_init(A *, C)
565 Init,
566 // C __c11_atomic_load(A *, int)
567 Load,
568 // void __atomic_load(A *, CP, int)
569 Copy,
570 // C __c11_atomic_add(A *, M, int)
571 Arithmetic,
572 // C __atomic_exchange_n(A *, CP, int)
573 Xchg,
574 // void __atomic_exchange(A *, C *, CP, int)
575 GNUXchg,
576 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
577 C11CmpXchg,
578 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
579 GNUCmpXchg
580 } Form = Init;
581 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
582 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
583 // where:
584 // C is an appropriate type,
585 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
586 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
587 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
588 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000589
Richard Smithff34d402012-04-12 05:08:17 +0000590 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
591 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
592 && "need to update code for modified C11 atomics");
593 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
594 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
595 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
596 Op == AtomicExpr::AO__atomic_store_n ||
597 Op == AtomicExpr::AO__atomic_exchange_n ||
598 Op == AtomicExpr::AO__atomic_compare_exchange_n;
599 bool IsAddSub = false;
600
601 switch (Op) {
602 case AtomicExpr::AO__c11_atomic_init:
603 Form = Init;
604 break;
605
606 case AtomicExpr::AO__c11_atomic_load:
607 case AtomicExpr::AO__atomic_load_n:
608 Form = Load;
609 break;
610
611 case AtomicExpr::AO__c11_atomic_store:
612 case AtomicExpr::AO__atomic_load:
613 case AtomicExpr::AO__atomic_store:
614 case AtomicExpr::AO__atomic_store_n:
615 Form = Copy;
616 break;
617
618 case AtomicExpr::AO__c11_atomic_fetch_add:
619 case AtomicExpr::AO__c11_atomic_fetch_sub:
620 case AtomicExpr::AO__atomic_fetch_add:
621 case AtomicExpr::AO__atomic_fetch_sub:
622 case AtomicExpr::AO__atomic_add_fetch:
623 case AtomicExpr::AO__atomic_sub_fetch:
624 IsAddSub = true;
625 // Fall through.
626 case AtomicExpr::AO__c11_atomic_fetch_and:
627 case AtomicExpr::AO__c11_atomic_fetch_or:
628 case AtomicExpr::AO__c11_atomic_fetch_xor:
629 case AtomicExpr::AO__atomic_fetch_and:
630 case AtomicExpr::AO__atomic_fetch_or:
631 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000632 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000633 case AtomicExpr::AO__atomic_and_fetch:
634 case AtomicExpr::AO__atomic_or_fetch:
635 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000636 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000637 Form = Arithmetic;
638 break;
639
640 case AtomicExpr::AO__c11_atomic_exchange:
641 case AtomicExpr::AO__atomic_exchange_n:
642 Form = Xchg;
643 break;
644
645 case AtomicExpr::AO__atomic_exchange:
646 Form = GNUXchg;
647 break;
648
649 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
650 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
651 Form = C11CmpXchg;
652 break;
653
654 case AtomicExpr::AO__atomic_compare_exchange:
655 case AtomicExpr::AO__atomic_compare_exchange_n:
656 Form = GNUCmpXchg;
657 break;
658 }
659
660 // Check we have the right number of arguments.
661 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000662 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000663 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000664 << TheCall->getCallee()->getSourceRange();
665 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000666 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
667 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000668 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000669 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000670 << TheCall->getCallee()->getSourceRange();
671 return ExprError();
672 }
673
Richard Smithff34d402012-04-12 05:08:17 +0000674 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000675 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000676 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
677 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
678 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000679 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000680 << Ptr->getType() << Ptr->getSourceRange();
681 return ExprError();
682 }
683
Richard Smithff34d402012-04-12 05:08:17 +0000684 // For a __c11 builtin, this should be a pointer to an _Atomic type.
685 QualType AtomTy = pointerType->getPointeeType(); // 'A'
686 QualType ValType = AtomTy; // 'C'
687 if (IsC11) {
688 if (!AtomTy->isAtomicType()) {
689 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
690 << Ptr->getType() << Ptr->getSourceRange();
691 return ExprError();
692 }
693 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000694 }
Eli Friedman276b0612011-10-11 02:20:01 +0000695
Richard Smithff34d402012-04-12 05:08:17 +0000696 // For an arithmetic operation, the implied arithmetic must be well-formed.
697 if (Form == Arithmetic) {
698 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
699 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
700 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
701 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
702 return ExprError();
703 }
704 if (!IsAddSub && !ValType->isIntegerType()) {
705 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
706 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
707 return ExprError();
708 }
709 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
710 // For __atomic_*_n operations, the value type must be a scalar integral or
711 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000712 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000713 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
714 return ExprError();
715 }
716
717 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
718 // For GNU atomics, require a trivially-copyable type. This is not part of
719 // the GNU atomics specification, but we enforce it for sanity.
720 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000721 << Ptr->getType() << Ptr->getSourceRange();
722 return ExprError();
723 }
724
Richard Smithff34d402012-04-12 05:08:17 +0000725 // FIXME: For any builtin other than a load, the ValType must not be
726 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000727
728 switch (ValType.getObjCLifetime()) {
729 case Qualifiers::OCL_None:
730 case Qualifiers::OCL_ExplicitNone:
731 // okay
732 break;
733
734 case Qualifiers::OCL_Weak:
735 case Qualifiers::OCL_Strong:
736 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000737 // FIXME: Can this happen? By this point, ValType should be known
738 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000739 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
740 << ValType << Ptr->getSourceRange();
741 return ExprError();
742 }
743
744 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000745 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000746 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000747 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000748 ResultType = Context.BoolTy;
749
Richard Smithff34d402012-04-12 05:08:17 +0000750 // The type of a parameter passed 'by value'. In the GNU atomics, such
751 // arguments are actually passed as pointers.
752 QualType ByValType = ValType; // 'CP'
753 if (!IsC11 && !IsN)
754 ByValType = Ptr->getType();
755
Eli Friedman276b0612011-10-11 02:20:01 +0000756 // The first argument --- the pointer --- has a fixed type; we
757 // deduce the types of the rest of the arguments accordingly. Walk
758 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000759 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000760 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000761 if (i < NumVals[Form] + 1) {
762 switch (i) {
763 case 1:
764 // The second argument is the non-atomic operand. For arithmetic, this
765 // is always passed by value, and for a compare_exchange it is always
766 // passed by address. For the rest, GNU uses by-address and C11 uses
767 // by-value.
768 assert(Form != Load);
769 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
770 Ty = ValType;
771 else if (Form == Copy || Form == Xchg)
772 Ty = ByValType;
773 else if (Form == Arithmetic)
774 Ty = Context.getPointerDiffType();
775 else
776 Ty = Context.getPointerType(ValType.getUnqualifiedType());
777 break;
778 case 2:
779 // The third argument to compare_exchange / GNU exchange is a
780 // (pointer to a) desired value.
781 Ty = ByValType;
782 break;
783 case 3:
784 // The fourth argument to GNU compare_exchange is a 'weak' flag.
785 Ty = Context.BoolTy;
786 break;
787 }
Eli Friedman276b0612011-10-11 02:20:01 +0000788 } else {
789 // The order(s) are always converted to int.
790 Ty = Context.IntTy;
791 }
Richard Smithff34d402012-04-12 05:08:17 +0000792
Eli Friedman276b0612011-10-11 02:20:01 +0000793 InitializedEntity Entity =
794 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000795 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000796 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
797 if (Arg.isInvalid())
798 return true;
799 TheCall->setArg(i, Arg.get());
800 }
801
Richard Smithff34d402012-04-12 05:08:17 +0000802 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000803 SmallVector<Expr*, 5> SubExprs;
804 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000805 switch (Form) {
806 case Init:
807 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000808 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000809 break;
810 case Load:
811 SubExprs.push_back(TheCall->getArg(1)); // Order
812 break;
813 case Copy:
814 case Arithmetic:
815 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000816 SubExprs.push_back(TheCall->getArg(2)); // Order
817 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000818 break;
819 case GNUXchg:
820 // Note, AtomicExpr::getVal2() has a special case for this atomic.
821 SubExprs.push_back(TheCall->getArg(3)); // Order
822 SubExprs.push_back(TheCall->getArg(1)); // Val1
823 SubExprs.push_back(TheCall->getArg(2)); // Val2
824 break;
825 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000826 SubExprs.push_back(TheCall->getArg(3)); // Order
827 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000828 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000829 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000830 break;
831 case GNUCmpXchg:
832 SubExprs.push_back(TheCall->getArg(4)); // Order
833 SubExprs.push_back(TheCall->getArg(1)); // Val1
834 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
835 SubExprs.push_back(TheCall->getArg(2)); // Val2
836 SubExprs.push_back(TheCall->getArg(3)); // Weak
837 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000838 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000839
840 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
841 SubExprs.data(), SubExprs.size(),
842 ResultType, Op,
843 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000844}
845
846
John McCall5f8d6042011-08-27 01:09:30 +0000847/// checkBuiltinArgument - Given a call to a builtin function, perform
848/// normal type-checking on the given argument, updating the call in
849/// place. This is useful when a builtin function requires custom
850/// type-checking for some of its arguments but not necessarily all of
851/// them.
852///
853/// Returns true on error.
854static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
855 FunctionDecl *Fn = E->getDirectCallee();
856 assert(Fn && "builtin call without direct callee!");
857
858 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
859 InitializedEntity Entity =
860 InitializedEntity::InitializeParameter(S.Context, Param);
861
862 ExprResult Arg = E->getArg(0);
863 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
864 if (Arg.isInvalid())
865 return true;
866
867 E->setArg(ArgIndex, Arg.take());
868 return false;
869}
870
Chris Lattner5caa3702009-05-08 06:58:22 +0000871/// SemaBuiltinAtomicOverloaded - We have a call to a function like
872/// __sync_fetch_and_add, which is an overloaded function based on the pointer
873/// type of its first argument. The main ActOnCallExpr routines have already
874/// promoted the types of arguments because all of these calls are prototyped as
875/// void(...).
876///
877/// This function goes through and does final semantic checking for these
878/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000879ExprResult
880Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000881 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000882 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
883 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
884
885 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000886 if (TheCall->getNumArgs() < 1) {
887 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
888 << 0 << 1 << TheCall->getNumArgs()
889 << TheCall->getCallee()->getSourceRange();
890 return ExprError();
891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattner5caa3702009-05-08 06:58:22 +0000893 // Inspect the first argument of the atomic builtin. This should always be
894 // a pointer type, whose element is an integral scalar or pointer type.
895 // Because it is a pointer type, we don't have to worry about any implicit
896 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000897 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000898 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000899 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
900 if (FirstArgResult.isInvalid())
901 return ExprError();
902 FirstArg = FirstArgResult.take();
903 TheCall->setArg(0, FirstArg);
904
John McCallf85e1932011-06-15 23:02:42 +0000905 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
906 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000907 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
908 << FirstArg->getType() << FirstArg->getSourceRange();
909 return ExprError();
910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
John McCallf85e1932011-06-15 23:02:42 +0000912 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000913 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000914 !ValType->isBlockPointerType()) {
915 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
916 << FirstArg->getType() << FirstArg->getSourceRange();
917 return ExprError();
918 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000919
John McCallf85e1932011-06-15 23:02:42 +0000920 switch (ValType.getObjCLifetime()) {
921 case Qualifiers::OCL_None:
922 case Qualifiers::OCL_ExplicitNone:
923 // okay
924 break;
925
926 case Qualifiers::OCL_Weak:
927 case Qualifiers::OCL_Strong:
928 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000929 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000930 << ValType << FirstArg->getSourceRange();
931 return ExprError();
932 }
933
John McCallb45ae252011-10-05 07:41:44 +0000934 // Strip any qualifiers off ValType.
935 ValType = ValType.getUnqualifiedType();
936
Chandler Carruth8d13d222010-07-18 20:54:12 +0000937 // The majority of builtins return a value, but a few have special return
938 // types, so allow them to override appropriately below.
939 QualType ResultType = ValType;
940
Chris Lattner5caa3702009-05-08 06:58:22 +0000941 // We need to figure out which concrete builtin this maps onto. For example,
942 // __sync_fetch_and_add with a 2 byte object turns into
943 // __sync_fetch_and_add_2.
944#define BUILTIN_ROW(x) \
945 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
946 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner5caa3702009-05-08 06:58:22 +0000948 static const unsigned BuiltinIndices[][5] = {
949 BUILTIN_ROW(__sync_fetch_and_add),
950 BUILTIN_ROW(__sync_fetch_and_sub),
951 BUILTIN_ROW(__sync_fetch_and_or),
952 BUILTIN_ROW(__sync_fetch_and_and),
953 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner5caa3702009-05-08 06:58:22 +0000955 BUILTIN_ROW(__sync_add_and_fetch),
956 BUILTIN_ROW(__sync_sub_and_fetch),
957 BUILTIN_ROW(__sync_and_and_fetch),
958 BUILTIN_ROW(__sync_or_and_fetch),
959 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner5caa3702009-05-08 06:58:22 +0000961 BUILTIN_ROW(__sync_val_compare_and_swap),
962 BUILTIN_ROW(__sync_bool_compare_and_swap),
963 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000964 BUILTIN_ROW(__sync_lock_release),
965 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000966 };
Mike Stump1eb44332009-09-09 15:08:12 +0000967#undef BUILTIN_ROW
968
Chris Lattner5caa3702009-05-08 06:58:22 +0000969 // Determine the index of the size.
970 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000971 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000972 case 1: SizeIndex = 0; break;
973 case 2: SizeIndex = 1; break;
974 case 4: SizeIndex = 2; break;
975 case 8: SizeIndex = 3; break;
976 case 16: SizeIndex = 4; break;
977 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000978 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
979 << FirstArg->getType() << FirstArg->getSourceRange();
980 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner5caa3702009-05-08 06:58:22 +0000983 // Each of these builtins has one pointer argument, followed by some number of
984 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
985 // that we ignore. Find out which row of BuiltinIndices to read from as well
986 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000987 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000988 unsigned BuiltinIndex, NumFixed = 1;
989 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000990 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000991 case Builtin::BI__sync_fetch_and_add:
992 case Builtin::BI__sync_fetch_and_add_1:
993 case Builtin::BI__sync_fetch_and_add_2:
994 case Builtin::BI__sync_fetch_and_add_4:
995 case Builtin::BI__sync_fetch_and_add_8:
996 case Builtin::BI__sync_fetch_and_add_16:
997 BuiltinIndex = 0;
998 break;
999
1000 case Builtin::BI__sync_fetch_and_sub:
1001 case Builtin::BI__sync_fetch_and_sub_1:
1002 case Builtin::BI__sync_fetch_and_sub_2:
1003 case Builtin::BI__sync_fetch_and_sub_4:
1004 case Builtin::BI__sync_fetch_and_sub_8:
1005 case Builtin::BI__sync_fetch_and_sub_16:
1006 BuiltinIndex = 1;
1007 break;
1008
1009 case Builtin::BI__sync_fetch_and_or:
1010 case Builtin::BI__sync_fetch_and_or_1:
1011 case Builtin::BI__sync_fetch_and_or_2:
1012 case Builtin::BI__sync_fetch_and_or_4:
1013 case Builtin::BI__sync_fetch_and_or_8:
1014 case Builtin::BI__sync_fetch_and_or_16:
1015 BuiltinIndex = 2;
1016 break;
1017
1018 case Builtin::BI__sync_fetch_and_and:
1019 case Builtin::BI__sync_fetch_and_and_1:
1020 case Builtin::BI__sync_fetch_and_and_2:
1021 case Builtin::BI__sync_fetch_and_and_4:
1022 case Builtin::BI__sync_fetch_and_and_8:
1023 case Builtin::BI__sync_fetch_and_and_16:
1024 BuiltinIndex = 3;
1025 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregora9766412011-11-28 16:30:08 +00001027 case Builtin::BI__sync_fetch_and_xor:
1028 case Builtin::BI__sync_fetch_and_xor_1:
1029 case Builtin::BI__sync_fetch_and_xor_2:
1030 case Builtin::BI__sync_fetch_and_xor_4:
1031 case Builtin::BI__sync_fetch_and_xor_8:
1032 case Builtin::BI__sync_fetch_and_xor_16:
1033 BuiltinIndex = 4;
1034 break;
1035
1036 case Builtin::BI__sync_add_and_fetch:
1037 case Builtin::BI__sync_add_and_fetch_1:
1038 case Builtin::BI__sync_add_and_fetch_2:
1039 case Builtin::BI__sync_add_and_fetch_4:
1040 case Builtin::BI__sync_add_and_fetch_8:
1041 case Builtin::BI__sync_add_and_fetch_16:
1042 BuiltinIndex = 5;
1043 break;
1044
1045 case Builtin::BI__sync_sub_and_fetch:
1046 case Builtin::BI__sync_sub_and_fetch_1:
1047 case Builtin::BI__sync_sub_and_fetch_2:
1048 case Builtin::BI__sync_sub_and_fetch_4:
1049 case Builtin::BI__sync_sub_and_fetch_8:
1050 case Builtin::BI__sync_sub_and_fetch_16:
1051 BuiltinIndex = 6;
1052 break;
1053
1054 case Builtin::BI__sync_and_and_fetch:
1055 case Builtin::BI__sync_and_and_fetch_1:
1056 case Builtin::BI__sync_and_and_fetch_2:
1057 case Builtin::BI__sync_and_and_fetch_4:
1058 case Builtin::BI__sync_and_and_fetch_8:
1059 case Builtin::BI__sync_and_and_fetch_16:
1060 BuiltinIndex = 7;
1061 break;
1062
1063 case Builtin::BI__sync_or_and_fetch:
1064 case Builtin::BI__sync_or_and_fetch_1:
1065 case Builtin::BI__sync_or_and_fetch_2:
1066 case Builtin::BI__sync_or_and_fetch_4:
1067 case Builtin::BI__sync_or_and_fetch_8:
1068 case Builtin::BI__sync_or_and_fetch_16:
1069 BuiltinIndex = 8;
1070 break;
1071
1072 case Builtin::BI__sync_xor_and_fetch:
1073 case Builtin::BI__sync_xor_and_fetch_1:
1074 case Builtin::BI__sync_xor_and_fetch_2:
1075 case Builtin::BI__sync_xor_and_fetch_4:
1076 case Builtin::BI__sync_xor_and_fetch_8:
1077 case Builtin::BI__sync_xor_and_fetch_16:
1078 BuiltinIndex = 9;
1079 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Chris Lattner5caa3702009-05-08 06:58:22 +00001081 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001082 case Builtin::BI__sync_val_compare_and_swap_1:
1083 case Builtin::BI__sync_val_compare_and_swap_2:
1084 case Builtin::BI__sync_val_compare_and_swap_4:
1085 case Builtin::BI__sync_val_compare_and_swap_8:
1086 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001087 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001088 NumFixed = 2;
1089 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001090
Chris Lattner5caa3702009-05-08 06:58:22 +00001091 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001092 case Builtin::BI__sync_bool_compare_and_swap_1:
1093 case Builtin::BI__sync_bool_compare_and_swap_2:
1094 case Builtin::BI__sync_bool_compare_and_swap_4:
1095 case Builtin::BI__sync_bool_compare_and_swap_8:
1096 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001097 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001098 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001099 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001100 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001101
1102 case Builtin::BI__sync_lock_test_and_set:
1103 case Builtin::BI__sync_lock_test_and_set_1:
1104 case Builtin::BI__sync_lock_test_and_set_2:
1105 case Builtin::BI__sync_lock_test_and_set_4:
1106 case Builtin::BI__sync_lock_test_and_set_8:
1107 case Builtin::BI__sync_lock_test_and_set_16:
1108 BuiltinIndex = 12;
1109 break;
1110
Chris Lattner5caa3702009-05-08 06:58:22 +00001111 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001112 case Builtin::BI__sync_lock_release_1:
1113 case Builtin::BI__sync_lock_release_2:
1114 case Builtin::BI__sync_lock_release_4:
1115 case Builtin::BI__sync_lock_release_8:
1116 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001117 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001118 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001119 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001120 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001121
1122 case Builtin::BI__sync_swap:
1123 case Builtin::BI__sync_swap_1:
1124 case Builtin::BI__sync_swap_2:
1125 case Builtin::BI__sync_swap_4:
1126 case Builtin::BI__sync_swap_8:
1127 case Builtin::BI__sync_swap_16:
1128 BuiltinIndex = 14;
1129 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001130 }
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Chris Lattner5caa3702009-05-08 06:58:22 +00001132 // Now that we know how many fixed arguments we expect, first check that we
1133 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001134 if (TheCall->getNumArgs() < 1+NumFixed) {
1135 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1136 << 0 << 1+NumFixed << TheCall->getNumArgs()
1137 << TheCall->getCallee()->getSourceRange();
1138 return ExprError();
1139 }
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001141 // Get the decl for the concrete builtin from this, we can tell what the
1142 // concrete integer type we should convert to is.
1143 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1144 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1145 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001146 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001147 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1148 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001149
John McCallf871d0c2010-08-07 06:22:56 +00001150 // The first argument --- the pointer --- has a fixed type; we
1151 // deduce the types of the rest of the arguments accordingly. Walk
1152 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001153 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001154 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Chris Lattner5caa3702009-05-08 06:58:22 +00001156 // GCC does an implicit conversion to the pointer or integer ValType. This
1157 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001158 // Initialize the argument.
1159 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1160 ValType, /*consume*/ false);
1161 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001162 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001163 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Chris Lattner5caa3702009-05-08 06:58:22 +00001165 // Okay, we have something that *can* be converted to the right type. Check
1166 // to see if there is a potentially weird extension going on here. This can
1167 // happen when you do an atomic operation on something like an char* and
1168 // pass in 42. The 42 gets converted to char. This is even more strange
1169 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001170 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001171 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001174 ASTContext& Context = this->getASTContext();
1175
1176 // Create a new DeclRefExpr to refer to the new decl.
1177 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1178 Context,
1179 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001180 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001181 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001182 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001183 DRE->getLocation(),
1184 NewBuiltinDecl->getType(),
1185 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner5caa3702009-05-08 06:58:22 +00001187 // Set the callee in the CallExpr.
1188 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001189 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001190 if (PromotedCall.isInvalid())
1191 return ExprError();
1192 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001194 // Change the result type of the call to match the original value type. This
1195 // is arbitrary, but the codegen for these builtins ins design to handle it
1196 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001197 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001198
1199 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001200}
1201
Chris Lattner69039812009-02-18 06:01:06 +00001202/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001203/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001204/// Note: It might also make sense to do the UTF-16 conversion here (would
1205/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001206bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001207 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001208 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1209
Douglas Gregor5cee1192011-07-27 05:40:30 +00001210 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001211 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1212 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001213 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001216 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001217 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001218 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001219 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001220 const UTF8 *FromPtr = (UTF8 *)String.data();
1221 UTF16 *ToPtr = &ToBuf[0];
1222
1223 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1224 &ToPtr, ToPtr + NumBytes,
1225 strictConversion);
1226 // Check for conversion failure.
1227 if (Result != conversionOK)
1228 Diag(Arg->getLocStart(),
1229 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1230 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001231 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001232}
1233
Chris Lattnerc27c6652007-12-20 00:05:45 +00001234/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1235/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001236bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1237 Expr *Fn = TheCall->getCallee();
1238 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001239 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001240 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001241 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1242 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001243 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001244 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001245 return true;
1246 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001247
1248 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001249 return Diag(TheCall->getLocEnd(),
1250 diag::err_typecheck_call_too_few_args_at_least)
1251 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001252 }
1253
John McCall5f8d6042011-08-27 01:09:30 +00001254 // Type-check the first argument normally.
1255 if (checkBuiltinArgument(*this, TheCall, 0))
1256 return true;
1257
Chris Lattnerc27c6652007-12-20 00:05:45 +00001258 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001259 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001260 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001261 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001262 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001263 else if (FunctionDecl *FD = getCurFunctionDecl())
1264 isVariadic = FD->isVariadic();
1265 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001266 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattnerc27c6652007-12-20 00:05:45 +00001268 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001269 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1270 return true;
1271 }
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chris Lattner30ce3442007-12-19 23:59:04 +00001273 // Verify that the second argument to the builtin is the last argument of the
1274 // current function or method.
1275 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001276 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Anders Carlsson88cf2262008-02-11 04:20:54 +00001278 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1279 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001280 // FIXME: This isn't correct for methods (results in bogus warning).
1281 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001282 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001283 if (CurBlock)
1284 LastArg = *(CurBlock->TheDecl->param_end()-1);
1285 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001286 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001287 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001288 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001289 SecondArgIsLastNamedArgument = PV == LastArg;
1290 }
1291 }
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Chris Lattner30ce3442007-12-19 23:59:04 +00001293 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001294 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001295 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1296 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001297}
Chris Lattner30ce3442007-12-19 23:59:04 +00001298
Chris Lattner1b9a0792007-12-20 00:26:33 +00001299/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1300/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001301bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1302 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001303 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001304 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001305 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001306 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001307 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001308 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001309 << SourceRange(TheCall->getArg(2)->getLocStart(),
1310 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001311
John Wiegley429bb272011-04-08 18:41:53 +00001312 ExprResult OrigArg0 = TheCall->getArg(0);
1313 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001314
Chris Lattner1b9a0792007-12-20 00:26:33 +00001315 // Do standard promotions between the two arguments, returning their common
1316 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001317 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001318 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1319 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001320
1321 // Make sure any conversions are pushed back into the call; this is
1322 // type safe since unordered compare builtins are declared as "_Bool
1323 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001324 TheCall->setArg(0, OrigArg0.get());
1325 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001326
John Wiegley429bb272011-04-08 18:41:53 +00001327 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001328 return false;
1329
Chris Lattner1b9a0792007-12-20 00:26:33 +00001330 // If the common type isn't a real floating type, then the arguments were
1331 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001332 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001333 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001334 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001335 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1336 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Chris Lattner1b9a0792007-12-20 00:26:33 +00001338 return false;
1339}
1340
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001341/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1342/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001343/// to check everything. We expect the last argument to be a floating point
1344/// value.
1345bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1346 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001347 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001348 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001349 if (TheCall->getNumArgs() > NumArgs)
1350 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001351 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001352 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001353 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001354 (*(TheCall->arg_end()-1))->getLocEnd());
1355
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001356 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Eli Friedman9ac6f622009-08-31 20:06:00 +00001358 if (OrigArg->isTypeDependent())
1359 return false;
1360
Chris Lattner81368fb2010-05-06 05:50:07 +00001361 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001362 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001363 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001364 diag::err_typecheck_call_invalid_unary_fp)
1365 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner81368fb2010-05-06 05:50:07 +00001367 // If this is an implicit conversion from float -> double, remove it.
1368 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1369 Expr *CastArg = Cast->getSubExpr();
1370 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1371 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1372 "promotion from float to double is the only expected cast here");
1373 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001374 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001375 }
1376 }
1377
Eli Friedman9ac6f622009-08-31 20:06:00 +00001378 return false;
1379}
1380
Eli Friedmand38617c2008-05-14 19:38:39 +00001381/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1382// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001383ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001384 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001385 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001386 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001387 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001388 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001389
Nate Begeman37b6a572010-06-08 00:16:34 +00001390 // Determine which of the following types of shufflevector we're checking:
1391 // 1) unary, vector mask: (lhs, mask)
1392 // 2) binary, vector mask: (lhs, rhs, mask)
1393 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1394 QualType resType = TheCall->getArg(0)->getType();
1395 unsigned numElements = 0;
1396
Douglas Gregorcde01732009-05-19 22:10:17 +00001397 if (!TheCall->getArg(0)->isTypeDependent() &&
1398 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001399 QualType LHSType = TheCall->getArg(0)->getType();
1400 QualType RHSType = TheCall->getArg(1)->getType();
1401
1402 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001403 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001404 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001405 TheCall->getArg(1)->getLocEnd());
1406 return ExprError();
1407 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001408
1409 numElements = LHSType->getAs<VectorType>()->getNumElements();
1410 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Nate Begeman37b6a572010-06-08 00:16:34 +00001412 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1413 // with mask. If so, verify that RHS is an integer vector type with the
1414 // same number of elts as lhs.
1415 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001416 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001417 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1418 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1419 << SourceRange(TheCall->getArg(1)->getLocStart(),
1420 TheCall->getArg(1)->getLocEnd());
1421 numResElements = numElements;
1422 }
1423 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001424 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001425 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001426 TheCall->getArg(1)->getLocEnd());
1427 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001428 } else if (numElements != numResElements) {
1429 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001430 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001431 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001432 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001433 }
1434
1435 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001436 if (TheCall->getArg(i)->isTypeDependent() ||
1437 TheCall->getArg(i)->isValueDependent())
1438 continue;
1439
Nate Begeman37b6a572010-06-08 00:16:34 +00001440 llvm::APSInt Result(32);
1441 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1442 return ExprError(Diag(TheCall->getLocStart(),
1443 diag::err_shufflevector_nonconstant_argument)
1444 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001445
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001446 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001447 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001448 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001449 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001450 }
1451
Chris Lattner5f9e2722011-07-23 10:55:15 +00001452 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001453
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001454 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001455 exprs.push_back(TheCall->getArg(i));
1456 TheCall->setArg(i, 0);
1457 }
1458
Nate Begemana88dc302009-08-12 02:10:25 +00001459 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001460 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001461 TheCall->getCallee()->getLocStart(),
1462 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001463}
Chris Lattner30ce3442007-12-19 23:59:04 +00001464
Daniel Dunbar4493f792008-07-21 22:59:13 +00001465/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1466// This is declared to take (const void*, ...) and can take two
1467// optional constant int args.
1468bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001469 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001470
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001471 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001472 return Diag(TheCall->getLocEnd(),
1473 diag::err_typecheck_call_too_many_args_at_most)
1474 << 0 /*function call*/ << 3 << NumArgs
1475 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001476
1477 // Argument 0 is checked for us and the remaining arguments must be
1478 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001479 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001480 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001481
Eli Friedman9aef7262009-12-04 00:30:06 +00001482 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001483 if (SemaBuiltinConstantArg(TheCall, i, Result))
1484 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Daniel Dunbar4493f792008-07-21 22:59:13 +00001486 // FIXME: gcc issues a warning and rewrites these to 0. These
1487 // seems especially odd for the third argument since the default
1488 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001489 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001490 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001491 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001492 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001493 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001494 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001495 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001496 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001497 }
1498 }
1499
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001500 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001501}
1502
Eric Christopher691ebc32010-04-17 02:26:23 +00001503/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1504/// TheCall is a constant expression.
1505bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1506 llvm::APSInt &Result) {
1507 Expr *Arg = TheCall->getArg(ArgNum);
1508 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1509 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1510
1511 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1512
1513 if (!Arg->isIntegerConstantExpr(Result, Context))
1514 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001515 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001516
Chris Lattner21fb98e2009-09-23 06:06:36 +00001517 return false;
1518}
1519
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001520/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1521/// int type). This simply type checks that type is one of the defined
1522/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001523// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001524bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001525 llvm::APSInt Result;
1526
1527 // Check constant-ness first.
1528 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1529 return true;
1530
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001531 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001532 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001533 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1534 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001535 }
1536
1537 return false;
1538}
1539
Eli Friedman586d6a82009-05-03 06:04:26 +00001540/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001541/// This checks that val is a constant 1.
1542bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1543 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001544 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001545
Eric Christopher691ebc32010-04-17 02:26:23 +00001546 // TODO: This is less than ideal. Overload this to take a value.
1547 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1548 return true;
1549
1550 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001551 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1552 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1553
1554 return false;
1555}
1556
Richard Smith831421f2012-06-25 20:30:08 +00001557// Determine if an expression is a string literal or constant string.
1558// If this function returns false on the arguments to a function expecting a
1559// format string, we will usually need to emit a warning.
1560// True string literals are then checked by CheckFormatString.
1561Sema::StringLiteralCheckType
1562Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1563 unsigned NumArgs, bool HasVAListArg,
1564 unsigned format_idx, unsigned firstDataArg,
1565 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001566 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001567 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001568 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001569
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001570 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001571
David Blaikiea73cdcb2012-02-10 21:07:25 +00001572 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1573 // Technically -Wformat-nonliteral does not warn about this case.
1574 // The behavior of printf and friends in this case is implementation
1575 // dependent. Ideally if the format string cannot be null then
1576 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001577 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001578
Ted Kremenekd30ef872009-01-12 23:09:09 +00001579 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001580 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001581 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001582 // The expression is a literal if both sub-expressions were, and it was
1583 // completely checked only if both sub-expressions were checked.
1584 const AbstractConditionalOperator *C =
1585 cast<AbstractConditionalOperator>(E);
1586 StringLiteralCheckType Left =
1587 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1588 HasVAListArg, format_idx, firstDataArg,
1589 Type, inFunctionCall);
1590 if (Left == SLCT_NotALiteral)
1591 return SLCT_NotALiteral;
1592 StringLiteralCheckType Right =
1593 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1594 HasVAListArg, format_idx, firstDataArg,
1595 Type, inFunctionCall);
1596 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001597 }
1598
1599 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001600 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1601 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001602 }
1603
John McCall56ca35d2011-02-17 10:25:35 +00001604 case Stmt::OpaqueValueExprClass:
1605 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1606 E = src;
1607 goto tryAgain;
1608 }
Richard Smith831421f2012-06-25 20:30:08 +00001609 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001610
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001611 case Stmt::PredefinedExprClass:
1612 // While __func__, etc., are technically not string literals, they
1613 // cannot contain format specifiers and thus are not a security
1614 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001615 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001616
Ted Kremenek082d9362009-03-20 21:35:28 +00001617 case Stmt::DeclRefExprClass: {
1618 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Ted Kremenek082d9362009-03-20 21:35:28 +00001620 // As an exception, do not flag errors for variables binding to
1621 // const string literals.
1622 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1623 bool isConstant = false;
1624 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001625
Ted Kremenek082d9362009-03-20 21:35:28 +00001626 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1627 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001628 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001629 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001630 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001631 } else if (T->isObjCObjectPointerType()) {
1632 // In ObjC, there is usually no "const ObjectPointer" type,
1633 // so don't check if the pointee type is constant.
1634 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001635 }
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Ted Kremenek082d9362009-03-20 21:35:28 +00001637 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001638 if (const Expr *Init = VD->getAnyInitializer()) {
1639 // Look through initializers like const char c[] = { "foo" }
1640 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1641 if (InitList->isStringLiteralInit())
1642 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1643 }
Richard Smith831421f2012-06-25 20:30:08 +00001644 return checkFormatStringExpr(Init, Args, NumArgs,
1645 HasVAListArg, format_idx,
1646 firstDataArg, Type,
1647 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001648 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Anders Carlssond966a552009-06-28 19:55:58 +00001651 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1652 // special check to see if the format string is a function parameter
1653 // of the function calling the printf function. If the function
1654 // has an attribute indicating it is a printf-like function, then we
1655 // should suppress warnings concerning non-literals being used in a call
1656 // to a vprintf function. For example:
1657 //
1658 // void
1659 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1660 // va_list ap;
1661 // va_start(ap, fmt);
1662 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1663 // ...
1664 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001665 if (HasVAListArg) {
1666 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1667 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1668 int PVIndex = PV->getFunctionScopeIndex() + 1;
1669 for (specific_attr_iterator<FormatAttr>
1670 i = ND->specific_attr_begin<FormatAttr>(),
1671 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1672 FormatAttr *PVFormat = *i;
1673 // adjust for implicit parameter
1674 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1675 if (MD->isInstance())
1676 ++PVIndex;
1677 // We also check if the formats are compatible.
1678 // We can't pass a 'scanf' string to a 'printf' function.
1679 if (PVIndex == PVFormat->getFormatIdx() &&
1680 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001681 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001682 }
1683 }
1684 }
1685 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Richard Smith831421f2012-06-25 20:30:08 +00001688 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001689 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001690
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001691 case Stmt::CallExprClass:
1692 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001693 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001694 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1695 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1696 unsigned ArgIndex = FA->getFormatIdx();
1697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1698 if (MD->isInstance())
1699 --ArgIndex;
1700 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Richard Smith831421f2012-06-25 20:30:08 +00001702 return checkFormatStringExpr(Arg, Args, NumArgs,
1703 HasVAListArg, format_idx, firstDataArg,
1704 Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001705 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1706 unsigned BuiltinID = FD->getBuiltinID();
1707 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1708 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1709 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001710 return checkFormatStringExpr(Arg, Args, NumArgs,
1711 HasVAListArg, format_idx,
1712 firstDataArg, Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001713 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001714 }
1715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Richard Smith831421f2012-06-25 20:30:08 +00001717 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001718 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001719 case Stmt::ObjCStringLiteralClass:
1720 case Stmt::StringLiteralClass: {
1721 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Ted Kremenek082d9362009-03-20 21:35:28 +00001723 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001724 StrE = ObjCFExpr->getString();
1725 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001726 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Ted Kremenekd30ef872009-01-12 23:09:09 +00001728 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001729 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001730 firstDataArg, Type, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001731 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Richard Smith831421f2012-06-25 20:30:08 +00001734 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 default:
Richard Smith831421f2012-06-25 20:30:08 +00001738 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001739 }
1740}
1741
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001742void
Mike Stump1eb44332009-09-09 15:08:12 +00001743Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001744 const Expr * const *ExprArgs,
1745 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001746 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1747 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001748 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001749 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001750 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001751 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001752 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001753 }
1754}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001755
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001756Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1757 return llvm::StringSwitch<FormatStringType>(Format->getType())
1758 .Case("scanf", FST_Scanf)
1759 .Cases("printf", "printf0", FST_Printf)
1760 .Cases("NSString", "CFString", FST_NSString)
1761 .Case("strftime", FST_Strftime)
1762 .Case("strfmon", FST_Strfmon)
1763 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1764 .Default(FST_Unknown);
1765}
1766
Ted Kremenek826a3452010-07-16 02:11:22 +00001767/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1768/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001769/// Returns true if a format string has been fully checked.
1770bool Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1771 bool IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
1772 return CheckFormatArguments(Format, TheCall->getArgs(),
1773 TheCall->getNumArgs(),
1774 IsCXXMember, TheCall->getRParenLoc(),
1775 TheCall->getCallee()->getSourceRange());
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001776}
1777
Richard Smith831421f2012-06-25 20:30:08 +00001778bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001779 unsigned NumArgs, bool IsCXXMember,
1780 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001781 FormatStringInfo FSI;
1782 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1783 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1784 FSI.FirstDataArg, GetFormatStringType(Format),
1785 Loc, Range);
1786 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001787}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001788
Richard Smith831421f2012-06-25 20:30:08 +00001789bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001790 bool HasVAListArg, unsigned format_idx,
1791 unsigned firstDataArg, FormatStringType Type,
1792 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001793 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001794 if (format_idx >= NumArgs) {
1795 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001796 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001799 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Chris Lattner59907c42007-08-10 20:18:51 +00001801 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001802 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001803 // Dynamically generated format strings are difficult to
1804 // automatically vet at compile time. Requiring that format strings
1805 // are string literals: (1) permits the checking of format strings by
1806 // the compiler and thereby (2) can practically remove the source of
1807 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001808
Mike Stump1eb44332009-09-09 15:08:12 +00001809 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001810 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001811 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001812 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001813 StringLiteralCheckType CT =
1814 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1815 format_idx, firstDataArg, Type);
1816 if (CT != SLCT_NotALiteral)
1817 // Literal format string found, check done!
1818 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001819
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001820 // Strftime is particular as it always uses a single 'time' argument,
1821 // so it is safe to pass a non-literal string.
1822 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001823 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001824
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001825 // Do not emit diag when the string param is a macro expansion and the
1826 // format is either NSString or CFString. This is a hack to prevent
1827 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1828 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001829 if (Type == FST_NSString &&
1830 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001831 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001832
Chris Lattner655f1412009-04-29 04:59:47 +00001833 // If there are no arguments specified, warn with -Wformat-security, otherwise
1834 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001835 if (NumArgs == format_idx+1)
1836 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001837 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001838 << OrigFormatExpr->getSourceRange();
1839 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001840 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001841 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001842 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001843 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001844}
Ted Kremenek71895b92007-08-14 17:39:48 +00001845
Ted Kremeneke0e53132010-01-28 23:39:18 +00001846namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001847class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1848protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001849 Sema &S;
1850 const StringLiteral *FExpr;
1851 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001852 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001853 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001854 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001855 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001856 const Expr * const *Args;
1857 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001858 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001859 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001860 bool usesPositionalArgs;
1861 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001862 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001863public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001864 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001865 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001866 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001867 Expr **args, unsigned numArgs,
1868 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001869 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001870 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1871 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001872 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001873 usesPositionalArgs(false), atFirstArg(true),
1874 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001875 CoveredArgs.resize(numDataArgs);
1876 CoveredArgs.reset();
1877 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001878
Ted Kremenek07d161f2010-01-29 01:50:07 +00001879 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001880
Ted Kremenek826a3452010-07-16 02:11:22 +00001881 void HandleIncompleteSpecifier(const char *startSpecifier,
1882 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001883
1884 void HandleNonStandardLengthModifier(
1885 const analyze_format_string::LengthModifier &LM,
1886 const char *startSpecifier, unsigned specifierLen);
1887
1888 void HandleNonStandardConversionSpecifier(
1889 const analyze_format_string::ConversionSpecifier &CS,
1890 const char *startSpecifier, unsigned specifierLen);
1891
1892 void HandleNonStandardConversionSpecification(
1893 const analyze_format_string::LengthModifier &LM,
1894 const analyze_format_string::ConversionSpecifier &CS,
1895 const char *startSpecifier, unsigned specifierLen);
1896
Hans Wennborgf8562642012-03-09 10:10:54 +00001897 virtual void HandlePosition(const char *startPos, unsigned posLen);
1898
Ted Kremenekefaff192010-02-27 01:41:03 +00001899 virtual void HandleInvalidPosition(const char *startSpecifier,
1900 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001901 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001902
1903 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1904
Ted Kremeneke0e53132010-01-28 23:39:18 +00001905 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001906
Richard Trieu55733de2011-10-28 00:41:25 +00001907 template <typename Range>
1908 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1909 const Expr *ArgumentExpr,
1910 PartialDiagnostic PDiag,
1911 SourceLocation StringLoc,
1912 bool IsStringLocation, Range StringRange,
1913 FixItHint Fixit = FixItHint());
1914
Ted Kremenek826a3452010-07-16 02:11:22 +00001915protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001916 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1917 const char *startSpec,
1918 unsigned specifierLen,
1919 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001920
1921 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1922 const char *startSpec,
1923 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001924
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001925 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001926 CharSourceRange getSpecifierRange(const char *startSpecifier,
1927 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001928 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001929
Ted Kremenek0d277352010-01-29 01:06:55 +00001930 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001931
1932 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1933 const analyze_format_string::ConversionSpecifier &CS,
1934 const char *startSpecifier, unsigned specifierLen,
1935 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001936
1937 template <typename Range>
1938 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1939 bool IsStringLocation, Range StringRange,
1940 FixItHint Fixit = FixItHint());
1941
1942 void CheckPositionalAndNonpositionalArgs(
1943 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001944};
1945}
1946
Ted Kremenek826a3452010-07-16 02:11:22 +00001947SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001948 return OrigFormatExpr->getSourceRange();
1949}
1950
Ted Kremenek826a3452010-07-16 02:11:22 +00001951CharSourceRange CheckFormatHandler::
1952getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001953 SourceLocation Start = getLocationOfByte(startSpecifier);
1954 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1955
1956 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001957 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001958
1959 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001960}
1961
Ted Kremenek826a3452010-07-16 02:11:22 +00001962SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001963 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001964}
1965
Ted Kremenek826a3452010-07-16 02:11:22 +00001966void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1967 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001968 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1969 getLocationOfByte(startSpecifier),
1970 /*IsStringLocation*/true,
1971 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001972}
1973
Hans Wennborg76517422012-02-22 10:17:01 +00001974void CheckFormatHandler::HandleNonStandardLengthModifier(
1975 const analyze_format_string::LengthModifier &LM,
1976 const char *startSpecifier, unsigned specifierLen) {
1977 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001978 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001979 getLocationOfByte(LM.getStart()),
1980 /*IsStringLocation*/true,
1981 getSpecifierRange(startSpecifier, specifierLen));
1982}
1983
1984void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1985 const analyze_format_string::ConversionSpecifier &CS,
1986 const char *startSpecifier, unsigned specifierLen) {
1987 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001988 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001989 getLocationOfByte(CS.getStart()),
1990 /*IsStringLocation*/true,
1991 getSpecifierRange(startSpecifier, specifierLen));
1992}
1993
1994void CheckFormatHandler::HandleNonStandardConversionSpecification(
1995 const analyze_format_string::LengthModifier &LM,
1996 const analyze_format_string::ConversionSpecifier &CS,
1997 const char *startSpecifier, unsigned specifierLen) {
1998 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1999 << LM.toString() << CS.toString(),
2000 getLocationOfByte(LM.getStart()),
2001 /*IsStringLocation*/true,
2002 getSpecifierRange(startSpecifier, specifierLen));
2003}
2004
Hans Wennborgf8562642012-03-09 10:10:54 +00002005void CheckFormatHandler::HandlePosition(const char *startPos,
2006 unsigned posLen) {
2007 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2008 getLocationOfByte(startPos),
2009 /*IsStringLocation*/true,
2010 getSpecifierRange(startPos, posLen));
2011}
2012
Ted Kremenekefaff192010-02-27 01:41:03 +00002013void
Ted Kremenek826a3452010-07-16 02:11:22 +00002014CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2015 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002016 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2017 << (unsigned) p,
2018 getLocationOfByte(startPos), /*IsStringLocation*/true,
2019 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002020}
2021
Ted Kremenek826a3452010-07-16 02:11:22 +00002022void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002023 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2025 getLocationOfByte(startPos),
2026 /*IsStringLocation*/true,
2027 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002028}
2029
Ted Kremenek826a3452010-07-16 02:11:22 +00002030void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002031 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002032 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002033 EmitFormatDiagnostic(
2034 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2035 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2036 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002037 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002038}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002039
Ted Kremenek826a3452010-07-16 02:11:22 +00002040const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002041 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002042}
2043
2044void CheckFormatHandler::DoneProcessing() {
2045 // Does the number of data arguments exceed the number of
2046 // format conversions in the format string?
2047 if (!HasVAListArg) {
2048 // Find any arguments that weren't covered.
2049 CoveredArgs.flip();
2050 signed notCoveredArg = CoveredArgs.find_first();
2051 if (notCoveredArg >= 0) {
2052 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002053 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
2054 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2055 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2056 Loc,
2057 /*IsStringLocation*/false, getFormatStringRange());
2058 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002059 }
2060 }
2061}
2062
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002063bool
2064CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2065 SourceLocation Loc,
2066 const char *startSpec,
2067 unsigned specifierLen,
2068 const char *csStart,
2069 unsigned csLen) {
2070
2071 bool keepGoing = true;
2072 if (argIndex < NumDataArgs) {
2073 // Consider the argument coverered, even though the specifier doesn't
2074 // make sense.
2075 CoveredArgs.set(argIndex);
2076 }
2077 else {
2078 // If argIndex exceeds the number of data arguments we
2079 // don't issue a warning because that is just a cascade of warnings (and
2080 // they may have intended '%%' anyway). We don't want to continue processing
2081 // the format string after this point, however, as we will like just get
2082 // gibberish when trying to match arguments.
2083 keepGoing = false;
2084 }
2085
Richard Trieu55733de2011-10-28 00:41:25 +00002086 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2087 << StringRef(csStart, csLen),
2088 Loc, /*IsStringLocation*/true,
2089 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002090
2091 return keepGoing;
2092}
2093
Richard Trieu55733de2011-10-28 00:41:25 +00002094void
2095CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2096 const char *startSpec,
2097 unsigned specifierLen) {
2098 EmitFormatDiagnostic(
2099 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2100 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2101}
2102
Ted Kremenek666a1972010-07-26 19:45:42 +00002103bool
2104CheckFormatHandler::CheckNumArgs(
2105 const analyze_format_string::FormatSpecifier &FS,
2106 const analyze_format_string::ConversionSpecifier &CS,
2107 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2108
2109 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002110 PartialDiagnostic PDiag = FS.usesPositionalArg()
2111 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2112 << (argIndex+1) << NumDataArgs)
2113 : S.PDiag(diag::warn_printf_insufficient_data_args);
2114 EmitFormatDiagnostic(
2115 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2116 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002117 return false;
2118 }
2119 return true;
2120}
2121
Richard Trieu55733de2011-10-28 00:41:25 +00002122template<typename Range>
2123void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2124 SourceLocation Loc,
2125 bool IsStringLocation,
2126 Range StringRange,
2127 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002128 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002129 Loc, IsStringLocation, StringRange, FixIt);
2130}
2131
2132/// \brief If the format string is not within the funcion call, emit a note
2133/// so that the function call and string are in diagnostic messages.
2134///
2135/// \param inFunctionCall if true, the format string is within the function
2136/// call and only one diagnostic message will be produced. Otherwise, an
2137/// extra note will be emitted pointing to location of the format string.
2138///
2139/// \param ArgumentExpr the expression that is passed as the format string
2140/// argument in the function call. Used for getting locations when two
2141/// diagnostics are emitted.
2142///
2143/// \param PDiag the callee should already have provided any strings for the
2144/// diagnostic message. This function only adds locations and fixits
2145/// to diagnostics.
2146///
2147/// \param Loc primary location for diagnostic. If two diagnostics are
2148/// required, one will be at Loc and a new SourceLocation will be created for
2149/// the other one.
2150///
2151/// \param IsStringLocation if true, Loc points to the format string should be
2152/// used for the note. Otherwise, Loc points to the argument list and will
2153/// be used with PDiag.
2154///
2155/// \param StringRange some or all of the string to highlight. This is
2156/// templated so it can accept either a CharSourceRange or a SourceRange.
2157///
2158/// \param Fixit optional fix it hint for the format string.
2159template<typename Range>
2160void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2161 const Expr *ArgumentExpr,
2162 PartialDiagnostic PDiag,
2163 SourceLocation Loc,
2164 bool IsStringLocation,
2165 Range StringRange,
2166 FixItHint FixIt) {
2167 if (InFunctionCall)
2168 S.Diag(Loc, PDiag) << StringRange << FixIt;
2169 else {
2170 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2171 << ArgumentExpr->getSourceRange();
2172 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2173 diag::note_format_string_defined)
2174 << StringRange << FixIt;
2175 }
2176}
2177
Ted Kremenek826a3452010-07-16 02:11:22 +00002178//===--- CHECK: Printf format string checking ------------------------------===//
2179
2180namespace {
2181class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002182 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002183public:
2184 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2185 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002186 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002187 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002188 Expr **Args, unsigned NumArgs,
2189 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002190 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002191 numDataArgs, beg, hasVAListArg, Args, NumArgs,
2192 formatIdx, inFunctionCall), ObjCContext(isObjC) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002193
2194
2195 bool HandleInvalidPrintfConversionSpecifier(
2196 const analyze_printf::PrintfSpecifier &FS,
2197 const char *startSpecifier,
2198 unsigned specifierLen);
2199
2200 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2201 const char *startSpecifier,
2202 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002203 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2204 const char *StartSpecifier,
2205 unsigned SpecifierLen,
2206 const Expr *E);
2207
Ted Kremenek826a3452010-07-16 02:11:22 +00002208 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2209 const char *startSpecifier, unsigned specifierLen);
2210 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2211 const analyze_printf::OptionalAmount &Amt,
2212 unsigned type,
2213 const char *startSpecifier, unsigned specifierLen);
2214 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2215 const analyze_printf::OptionalFlag &flag,
2216 const char *startSpecifier, unsigned specifierLen);
2217 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2218 const analyze_printf::OptionalFlag &ignoredFlag,
2219 const analyze_printf::OptionalFlag &flag,
2220 const char *startSpecifier, unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002221 bool checkForCStrMembers(const analyze_printf::ArgTypeResult &ATR,
2222 const Expr *E, const CharSourceRange &CSR);
2223
Ted Kremenek826a3452010-07-16 02:11:22 +00002224};
2225}
2226
2227bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2228 const analyze_printf::PrintfSpecifier &FS,
2229 const char *startSpecifier,
2230 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002231 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002232 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002233
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002234 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2235 getLocationOfByte(CS.getStart()),
2236 startSpecifier, specifierLen,
2237 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002238}
2239
Ted Kremenek826a3452010-07-16 02:11:22 +00002240bool CheckPrintfHandler::HandleAmount(
2241 const analyze_format_string::OptionalAmount &Amt,
2242 unsigned k, const char *startSpecifier,
2243 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002244
2245 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002246 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002247 unsigned argIndex = Amt.getArgIndex();
2248 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002249 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2250 << k,
2251 getLocationOfByte(Amt.getStart()),
2252 /*IsStringLocation*/true,
2253 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002254 // Don't do any more checking. We will just emit
2255 // spurious errors.
2256 return false;
2257 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002258
Ted Kremenek0d277352010-01-29 01:06:55 +00002259 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002260 // Although not in conformance with C99, we also allow the argument to be
2261 // an 'unsigned int' as that is a reasonably safe case. GCC also
2262 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002263 CoveredArgs.set(argIndex);
2264 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002265 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002266
2267 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2268 assert(ATR.isValid());
2269
2270 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002271 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002272 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002273 << T << Arg->getSourceRange(),
2274 getLocationOfByte(Amt.getStart()),
2275 /*IsStringLocation*/true,
2276 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002277 // Don't do any more checking. We will just emit
2278 // spurious errors.
2279 return false;
2280 }
2281 }
2282 }
2283 return true;
2284}
Ted Kremenek0d277352010-01-29 01:06:55 +00002285
Tom Caree4ee9662010-06-17 19:00:27 +00002286void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002287 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002288 const analyze_printf::OptionalAmount &Amt,
2289 unsigned type,
2290 const char *startSpecifier,
2291 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002292 const analyze_printf::PrintfConversionSpecifier &CS =
2293 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002294
Richard Trieu55733de2011-10-28 00:41:25 +00002295 FixItHint fixit =
2296 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2297 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2298 Amt.getConstantLength()))
2299 : FixItHint();
2300
2301 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2302 << type << CS.toString(),
2303 getLocationOfByte(Amt.getStart()),
2304 /*IsStringLocation*/true,
2305 getSpecifierRange(startSpecifier, specifierLen),
2306 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002307}
2308
Ted Kremenek826a3452010-07-16 02:11:22 +00002309void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002310 const analyze_printf::OptionalFlag &flag,
2311 const char *startSpecifier,
2312 unsigned specifierLen) {
2313 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002314 const analyze_printf::PrintfConversionSpecifier &CS =
2315 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002316 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2317 << flag.toString() << CS.toString(),
2318 getLocationOfByte(flag.getPosition()),
2319 /*IsStringLocation*/true,
2320 getSpecifierRange(startSpecifier, specifierLen),
2321 FixItHint::CreateRemoval(
2322 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002323}
2324
2325void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002326 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002327 const analyze_printf::OptionalFlag &ignoredFlag,
2328 const analyze_printf::OptionalFlag &flag,
2329 const char *startSpecifier,
2330 unsigned specifierLen) {
2331 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002332 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2333 << ignoredFlag.toString() << flag.toString(),
2334 getLocationOfByte(ignoredFlag.getPosition()),
2335 /*IsStringLocation*/true,
2336 getSpecifierRange(startSpecifier, specifierLen),
2337 FixItHint::CreateRemoval(
2338 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002339}
2340
Richard Smith831421f2012-06-25 20:30:08 +00002341// Determines if the specified is a C++ class or struct containing
2342// a member with the specified name and kind (e.g. a CXXMethodDecl named
2343// "c_str()").
2344template<typename MemberKind>
2345static llvm::SmallPtrSet<MemberKind*, 1>
2346CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2347 const RecordType *RT = Ty->getAs<RecordType>();
2348 llvm::SmallPtrSet<MemberKind*, 1> Results;
2349
2350 if (!RT)
2351 return Results;
2352 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2353 if (!RD)
2354 return Results;
2355
2356 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2357 Sema::LookupMemberName);
2358
2359 // We just need to include all members of the right kind turned up by the
2360 // filter, at this point.
2361 if (S.LookupQualifiedName(R, RT->getDecl()))
2362 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2363 NamedDecl *decl = (*I)->getUnderlyingDecl();
2364 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2365 Results.insert(FK);
2366 }
2367 return Results;
2368}
2369
2370// Check if a (w)string was passed when a (w)char* was needed, and offer a
2371// better diagnostic if so. ATR is assumed to be valid.
2372// Returns true when a c_str() conversion method is found.
2373bool CheckPrintfHandler::checkForCStrMembers(
2374 const analyze_printf::ArgTypeResult &ATR, const Expr *E,
2375 const CharSourceRange &CSR) {
2376 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2377
2378 MethodSet Results =
2379 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2380
2381 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2382 MI != ME; ++MI) {
2383 const CXXMethodDecl *Method = *MI;
2384 if (Method->getNumParams() == 0 &&
2385 ATR.matchesType(S.Context, Method->getResultType())) {
2386 // FIXME: Suggest parens if the expression needs them.
2387 SourceLocation EndLoc =
2388 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2389 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2390 << "c_str()"
2391 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2392 return true;
2393 }
2394 }
2395
2396 return false;
2397}
2398
Ted Kremeneke0e53132010-01-28 23:39:18 +00002399bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002400CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002401 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002402 const char *startSpecifier,
2403 unsigned specifierLen) {
2404
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002405 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002406 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002407 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002408
Ted Kremenekbaa40062010-07-19 22:01:06 +00002409 if (FS.consumesDataArgument()) {
2410 if (atFirstArg) {
2411 atFirstArg = false;
2412 usesPositionalArgs = FS.usesPositionalArg();
2413 }
2414 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002415 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2416 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002417 return false;
2418 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002419 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002420
Ted Kremenekefaff192010-02-27 01:41:03 +00002421 // First check if the field width, precision, and conversion specifier
2422 // have matching data arguments.
2423 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2424 startSpecifier, specifierLen)) {
2425 return false;
2426 }
2427
2428 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2429 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002430 return false;
2431 }
2432
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002433 if (!CS.consumesDataArgument()) {
2434 // FIXME: Technically specifying a precision or field width here
2435 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002436 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002437 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002438
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002439 // Consume the argument.
2440 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002441 if (argIndex < NumDataArgs) {
2442 // The check to see if the argIndex is valid will come later.
2443 // We set the bit here because we may exit early from this
2444 // function if we encounter some other error.
2445 CoveredArgs.set(argIndex);
2446 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002447
2448 // Check for using an Objective-C specific conversion specifier
2449 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002450 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002451 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2452 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002453 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002454
Tom Caree4ee9662010-06-17 19:00:27 +00002455 // Check for invalid use of field width
2456 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002457 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002458 startSpecifier, specifierLen);
2459 }
2460
2461 // Check for invalid use of precision
2462 if (!FS.hasValidPrecision()) {
2463 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2464 startSpecifier, specifierLen);
2465 }
2466
2467 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002468 if (!FS.hasValidThousandsGroupingPrefix())
2469 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002470 if (!FS.hasValidLeadingZeros())
2471 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2472 if (!FS.hasValidPlusPrefix())
2473 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002474 if (!FS.hasValidSpacePrefix())
2475 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002476 if (!FS.hasValidAlternativeForm())
2477 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2478 if (!FS.hasValidLeftJustified())
2479 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2480
2481 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002482 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2483 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2484 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002485 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2486 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2487 startSpecifier, specifierLen);
2488
2489 // Check the length modifier is valid with the given conversion specifier.
2490 const LengthModifier &LM = FS.getLengthModifier();
2491 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2493 << LM.toString() << CS.toString(),
2494 getLocationOfByte(LM.getStart()),
2495 /*IsStringLocation*/true,
2496 getSpecifierRange(startSpecifier, specifierLen),
2497 FixItHint::CreateRemoval(
2498 getSpecifierRange(LM.getStart(),
2499 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002500 if (!FS.hasStandardLengthModifier())
2501 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002502 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002503 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2504 if (!FS.hasStandardLengthConversionCombination())
2505 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2506 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002507
2508 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002509 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002510 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002511 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2512 getLocationOfByte(CS.getStart()),
2513 /*IsStringLocation*/true,
2514 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002515 // Continue checking the other format specifiers.
2516 return true;
2517 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002518
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002519 // The remaining checks depend on the data arguments.
2520 if (HasVAListArg)
2521 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002522
Ted Kremenek666a1972010-07-26 19:45:42 +00002523 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002524 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002525
Richard Smith831421f2012-06-25 20:30:08 +00002526 return checkFormatExpr(FS, startSpecifier, specifierLen,
2527 getDataArg(argIndex));
2528}
2529
2530bool
2531CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2532 const char *StartSpecifier,
2533 unsigned SpecifierLen,
2534 const Expr *E) {
2535 using namespace analyze_format_string;
2536 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002537 // Now type check the data expression that matches the
2538 // format specifier.
Nico Weber339b9072012-01-31 01:43:25 +00002539 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
Jordan Rose50687312012-06-04 23:52:23 +00002540 ObjCContext);
Richard Smith831421f2012-06-25 20:30:08 +00002541 if (ATR.isValid() && !ATR.matchesType(S.Context, E->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002542 // Look through argument promotions for our error message's reported type.
2543 // This includes the integral and floating promotions, but excludes array
2544 // and function pointer decay; seeing that an argument intended to be a
2545 // string has type 'char [6]' is probably more confusing than 'char *'.
Richard Smith831421f2012-06-25 20:30:08 +00002546 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002547 if (ICE->getCastKind() == CK_IntegralCast ||
2548 ICE->getCastKind() == CK_FloatingCast) {
Richard Smith831421f2012-06-25 20:30:08 +00002549 E = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002550
2551 // Check if we didn't match because of an implicit cast from a 'char'
2552 // or 'short' to an 'int'. This is done because printf is a varargs
2553 // function.
2554 if (ICE->getType() == S.Context.IntTy ||
2555 ICE->getType() == S.Context.UnsignedIntTy) {
2556 // All further checking is done on the subexpression.
Richard Smith831421f2012-06-25 20:30:08 +00002557 if (ATR.matchesType(S.Context, E->getType()))
Jordan Roseee0259d2012-06-04 22:48:57 +00002558 return true;
2559 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002560 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002561 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002562
2563 // We may be able to offer a FixItHint if it is a supported type.
2564 PrintfSpecifier fixedFS = FS;
Richard Smith831421f2012-06-25 20:30:08 +00002565 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002566 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002567
2568 if (success) {
2569 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002570 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002571 llvm::raw_svector_ostream os(buf);
2572 fixedFS.toString(os);
2573
Richard Trieu55733de2011-10-28 00:41:25 +00002574 EmitFormatDiagnostic(
2575 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Richard Smith831421f2012-06-25 20:30:08 +00002576 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2577 << E->getSourceRange(),
2578 E->getLocStart(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002579 /*IsStringLocation*/false,
Richard Smith831421f2012-06-25 20:30:08 +00002580 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002581 FixItHint::CreateReplacement(
Richard Smith831421f2012-06-25 20:30:08 +00002582 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002583 os.str()));
Richard Smith831421f2012-06-25 20:30:08 +00002584 } else {
2585 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2586 SpecifierLen);
2587 // Since the warning for passing non-POD types to variadic functions
2588 // was deferred until now, we emit a warning for non-POD
2589 // arguments here.
2590 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2591 EmitFormatDiagnostic(
2592 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
2593 << S.getLangOpts().CPlusPlus0x
2594 << E->getType()
2595 << ATR.getRepresentativeTypeName(S.Context)
2596 << CSR
2597 << E->getSourceRange(),
2598 E->getLocStart(), /*IsStringLocation*/false, CSR);
2599
2600 checkForCStrMembers(ATR, E, CSR);
2601 } else
2602 EmitFormatDiagnostic(
2603 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2604 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2605 << CSR
2606 << E->getSourceRange(),
2607 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002608 }
2609 }
2610
Ted Kremeneke0e53132010-01-28 23:39:18 +00002611 return true;
2612}
2613
Ted Kremenek826a3452010-07-16 02:11:22 +00002614//===--- CHECK: Scanf format string checking ------------------------------===//
2615
2616namespace {
2617class CheckScanfHandler : public CheckFormatHandler {
2618public:
2619 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2620 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002621 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002622 Expr **Args, unsigned NumArgs,
2623 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002624 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002625 numDataArgs, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002626 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002627
2628 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2629 const char *startSpecifier,
2630 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002631
2632 bool HandleInvalidScanfConversionSpecifier(
2633 const analyze_scanf::ScanfSpecifier &FS,
2634 const char *startSpecifier,
2635 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002636
2637 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002638};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002639}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002640
Ted Kremenekb7c21012010-07-16 18:28:03 +00002641void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2642 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002643 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2644 getLocationOfByte(end), /*IsStringLocation*/true,
2645 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002646}
2647
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002648bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2649 const analyze_scanf::ScanfSpecifier &FS,
2650 const char *startSpecifier,
2651 unsigned specifierLen) {
2652
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002653 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002654 FS.getConversionSpecifier();
2655
2656 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2657 getLocationOfByte(CS.getStart()),
2658 startSpecifier, specifierLen,
2659 CS.getStart(), CS.getLength());
2660}
2661
Ted Kremenek826a3452010-07-16 02:11:22 +00002662bool CheckScanfHandler::HandleScanfSpecifier(
2663 const analyze_scanf::ScanfSpecifier &FS,
2664 const char *startSpecifier,
2665 unsigned specifierLen) {
2666
2667 using namespace analyze_scanf;
2668 using namespace analyze_format_string;
2669
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002670 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002671
Ted Kremenekbaa40062010-07-19 22:01:06 +00002672 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2673 // be used to decide if we are using positional arguments consistently.
2674 if (FS.consumesDataArgument()) {
2675 if (atFirstArg) {
2676 atFirstArg = false;
2677 usesPositionalArgs = FS.usesPositionalArg();
2678 }
2679 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002680 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2681 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002682 return false;
2683 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002684 }
2685
2686 // Check if the field with is non-zero.
2687 const OptionalAmount &Amt = FS.getFieldWidth();
2688 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2689 if (Amt.getConstantAmount() == 0) {
2690 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2691 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002692 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2693 getLocationOfByte(Amt.getStart()),
2694 /*IsStringLocation*/true, R,
2695 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002696 }
2697 }
2698
2699 if (!FS.consumesDataArgument()) {
2700 // FIXME: Technically specifying a precision or field width here
2701 // makes no sense. Worth issuing a warning at some point.
2702 return true;
2703 }
2704
2705 // Consume the argument.
2706 unsigned argIndex = FS.getArgIndex();
2707 if (argIndex < NumDataArgs) {
2708 // The check to see if the argIndex is valid will come later.
2709 // We set the bit here because we may exit early from this
2710 // function if we encounter some other error.
2711 CoveredArgs.set(argIndex);
2712 }
2713
Ted Kremenek1e51c202010-07-20 20:04:47 +00002714 // Check the length modifier is valid with the given conversion specifier.
2715 const LengthModifier &LM = FS.getLengthModifier();
2716 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002717 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2718 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2719 << LM.toString() << CS.toString()
2720 << getSpecifierRange(startSpecifier, specifierLen),
2721 getLocationOfByte(LM.getStart()),
2722 /*IsStringLocation*/true, R,
2723 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002724 }
2725
Hans Wennborg76517422012-02-22 10:17:01 +00002726 if (!FS.hasStandardLengthModifier())
2727 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002728 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002729 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2730 if (!FS.hasStandardLengthConversionCombination())
2731 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2732 specifierLen);
2733
Ted Kremenek826a3452010-07-16 02:11:22 +00002734 // The remaining checks depend on the data arguments.
2735 if (HasVAListArg)
2736 return true;
2737
Ted Kremenek666a1972010-07-26 19:45:42 +00002738 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002739 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002740
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002741 // Check that the argument type matches the format specifier.
2742 const Expr *Ex = getDataArg(argIndex);
2743 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2744 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2745 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002746 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002747 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002748
2749 if (success) {
2750 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002751 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002752 llvm::raw_svector_ostream os(buf);
2753 fixedFS.toString(os);
2754
2755 EmitFormatDiagnostic(
2756 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2757 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2758 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002759 Ex->getLocStart(),
2760 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002761 getSpecifierRange(startSpecifier, specifierLen),
2762 FixItHint::CreateReplacement(
2763 getSpecifierRange(startSpecifier, specifierLen),
2764 os.str()));
2765 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002766 EmitFormatDiagnostic(
2767 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002768 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002769 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002770 Ex->getLocStart(),
2771 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002772 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002773 }
2774 }
2775
Ted Kremenek826a3452010-07-16 02:11:22 +00002776 return true;
2777}
2778
2779void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002780 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002781 Expr **Args, unsigned NumArgs,
2782 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002783 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002784 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002785
Ted Kremeneke0e53132010-01-28 23:39:18 +00002786 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002787 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002788 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002789 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002790 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2791 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002792 return;
2793 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002794
Ted Kremeneke0e53132010-01-28 23:39:18 +00002795 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002796 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002797 const char *Str = StrRef.data();
2798 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002799 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002800
Ted Kremeneke0e53132010-01-28 23:39:18 +00002801 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002802 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002803 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002804 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002805 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2806 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002807 return;
2808 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002809
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002810 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002811 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002812 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002813 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002814 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002815
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002816 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002817 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002818 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002819 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002820 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002821 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002822 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002823
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002824 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002825 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002826 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002827 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002828}
2829
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002830//===--- CHECK: Standard memory functions ---------------------------------===//
2831
Douglas Gregor2a053a32011-05-03 20:05:22 +00002832/// \brief Determine whether the given type is a dynamic class type (e.g.,
2833/// whether it has a vtable).
2834static bool isDynamicClassType(QualType T) {
2835 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2836 if (CXXRecordDecl *Definition = Record->getDefinition())
2837 if (Definition->isDynamicClass())
2838 return true;
2839
2840 return false;
2841}
2842
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002843/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002844/// otherwise returns NULL.
2845static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002846 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002847 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2848 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2849 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002850
Chandler Carruth000d4282011-06-16 09:09:40 +00002851 return 0;
2852}
2853
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002854/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002855static QualType getSizeOfArgType(const Expr* E) {
2856 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2857 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2858 if (SizeOf->getKind() == clang::UETT_SizeOf)
2859 return SizeOf->getTypeOfArgument();
2860
2861 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002862}
2863
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002864/// \brief Check for dangerous or invalid arguments to memset().
2865///
Chandler Carruth929f0132011-06-03 06:23:57 +00002866/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002867/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2868/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002869///
2870/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002871void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002872 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002873 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002874 assert(BId != 0);
2875
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002876 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002877 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002878 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002879 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002880 return;
2881
Anna Zaks0a151a12012-01-17 00:37:07 +00002882 unsigned LastArg = (BId == Builtin::BImemset ||
2883 BId == Builtin::BIstrndup ? 1 : 2);
2884 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002885 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002886
2887 // We have special checking when the length is a sizeof expression.
2888 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2889 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2890 llvm::FoldingSetNodeID SizeOfArgID;
2891
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002892 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2893 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002894 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002895
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002896 QualType DestTy = Dest->getType();
2897 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2898 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002899
Chandler Carruth000d4282011-06-16 09:09:40 +00002900 // Never warn about void type pointers. This can be used to suppress
2901 // false positives.
2902 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002903 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002904
Chandler Carruth000d4282011-06-16 09:09:40 +00002905 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2906 // actually comparing the expressions for equality. Because computing the
2907 // expression IDs can be expensive, we only do this if the diagnostic is
2908 // enabled.
2909 if (SizeOfArg &&
2910 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2911 SizeOfArg->getExprLoc())) {
2912 // We only compute IDs for expressions if the warning is enabled, and
2913 // cache the sizeof arg's ID.
2914 if (SizeOfArgID == llvm::FoldingSetNodeID())
2915 SizeOfArg->Profile(SizeOfArgID, Context, true);
2916 llvm::FoldingSetNodeID DestID;
2917 Dest->Profile(DestID, Context, true);
2918 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002919 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2920 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002921 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002922 StringRef ReadableName = FnName->getName();
2923
Chandler Carruth000d4282011-06-16 09:09:40 +00002924 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002925 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002926 ActionIdx = 1; // If its an address-of operator, just remove it.
2927 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2928 ActionIdx = 2; // If the pointee's size is sizeof(char),
2929 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002930
2931 // If the function is defined as a builtin macro, do not show macro
2932 // expansion.
2933 SourceLocation SL = SizeOfArg->getExprLoc();
2934 SourceRange DSR = Dest->getSourceRange();
2935 SourceRange SSR = SizeOfArg->getSourceRange();
2936 SourceManager &SM = PP.getSourceManager();
2937
2938 if (SM.isMacroArgExpansion(SL)) {
2939 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
2940 SL = SM.getSpellingLoc(SL);
2941 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
2942 SM.getSpellingLoc(DSR.getEnd()));
2943 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
2944 SM.getSpellingLoc(SSR.getEnd()));
2945 }
2946
Anna Zaks90c78322012-05-30 23:14:52 +00002947 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00002948 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00002949 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00002950 << PointeeTy
2951 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00002952 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00002953 << SSR);
2954 DiagRuntimeBehavior(SL, SizeOfArg,
2955 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
2956 << ActionIdx
2957 << SSR);
2958
Chandler Carruth000d4282011-06-16 09:09:40 +00002959 break;
2960 }
2961 }
2962
2963 // Also check for cases where the sizeof argument is the exact same
2964 // type as the memory argument, and where it points to a user-defined
2965 // record type.
2966 if (SizeOfArgTy != QualType()) {
2967 if (PointeeTy->isRecordType() &&
2968 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2969 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2970 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2971 << FnName << SizeOfArgTy << ArgIdx
2972 << PointeeTy << Dest->getSourceRange()
2973 << LenExpr->getSourceRange());
2974 break;
2975 }
Nico Webere4a1c642011-06-14 16:14:58 +00002976 }
2977
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002978 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002979 if (isDynamicClassType(PointeeTy)) {
2980
2981 unsigned OperationType = 0;
2982 // "overwritten" if we're warning about the destination for any call
2983 // but memcmp; otherwise a verb appropriate to the call.
2984 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2985 if (BId == Builtin::BImemcpy)
2986 OperationType = 1;
2987 else if(BId == Builtin::BImemmove)
2988 OperationType = 2;
2989 else if (BId == Builtin::BImemcmp)
2990 OperationType = 3;
2991 }
2992
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002993 DiagRuntimeBehavior(
2994 Dest->getExprLoc(), Dest,
2995 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002996 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002997 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002998 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002999 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003000 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3001 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003002 DiagRuntimeBehavior(
3003 Dest->getExprLoc(), Dest,
3004 PDiag(diag::warn_arc_object_memaccess)
3005 << ArgIdx << FnName << PointeeTy
3006 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003007 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003008 continue;
John McCallf85e1932011-06-15 23:02:42 +00003009
3010 DiagRuntimeBehavior(
3011 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003012 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003013 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3014 break;
3015 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003016 }
3017}
3018
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003019// A little helper routine: ignore addition and subtraction of integer literals.
3020// This intentionally does not ignore all integer constant expressions because
3021// we don't want to remove sizeof().
3022static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3023 Ex = Ex->IgnoreParenCasts();
3024
3025 for (;;) {
3026 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3027 if (!BO || !BO->isAdditiveOp())
3028 break;
3029
3030 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3031 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3032
3033 if (isa<IntegerLiteral>(RHS))
3034 Ex = LHS;
3035 else if (isa<IntegerLiteral>(LHS))
3036 Ex = RHS;
3037 else
3038 break;
3039 }
3040
3041 return Ex;
3042}
3043
3044// Warn if the user has made the 'size' argument to strlcpy or strlcat
3045// be the size of the source, instead of the destination.
3046void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3047 IdentifierInfo *FnName) {
3048
3049 // Don't crash if the user has the wrong number of arguments
3050 if (Call->getNumArgs() != 3)
3051 return;
3052
3053 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3054 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3055 const Expr *CompareWithSrc = NULL;
3056
3057 // Look for 'strlcpy(dst, x, sizeof(x))'
3058 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3059 CompareWithSrc = Ex;
3060 else {
3061 // Look for 'strlcpy(dst, x, strlen(x))'
3062 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003063 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003064 && SizeCall->getNumArgs() == 1)
3065 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3066 }
3067 }
3068
3069 if (!CompareWithSrc)
3070 return;
3071
3072 // Determine if the argument to sizeof/strlen is equal to the source
3073 // argument. In principle there's all kinds of things you could do
3074 // here, for instance creating an == expression and evaluating it with
3075 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3076 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3077 if (!SrcArgDRE)
3078 return;
3079
3080 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3081 if (!CompareWithSrcDRE ||
3082 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3083 return;
3084
3085 const Expr *OriginalSizeArg = Call->getArg(2);
3086 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3087 << OriginalSizeArg->getSourceRange() << FnName;
3088
3089 // Output a FIXIT hint if the destination is an array (rather than a
3090 // pointer to an array). This could be enhanced to handle some
3091 // pointers if we know the actual size, like if DstArg is 'array+2'
3092 // we could say 'sizeof(array)-2'.
3093 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00003094 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003095
Ted Kremenek8f746222011-08-18 22:48:41 +00003096 // Only handle constant-sized or VLAs, but not flexible members.
3097 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3098 // Only issue the FIXIT for arrays of size > 1.
3099 if (CAT->getSize().getSExtValue() <= 1)
3100 return;
3101 } else if (!DstArgTy->isVariableArrayType()) {
3102 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003103 }
Ted Kremenek8f746222011-08-18 22:48:41 +00003104
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003105 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003106 llvm::raw_svector_ostream OS(sizeString);
3107 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00003108 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003109 OS << ")";
3110
3111 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3112 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3113 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003114}
3115
Anna Zaksc36bedc2012-02-01 19:08:57 +00003116/// Check if two expressions refer to the same declaration.
3117static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3118 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3119 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3120 return D1->getDecl() == D2->getDecl();
3121 return false;
3122}
3123
3124static const Expr *getStrlenExprArg(const Expr *E) {
3125 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3126 const FunctionDecl *FD = CE->getDirectCallee();
3127 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3128 return 0;
3129 return CE->getArg(0)->IgnoreParenCasts();
3130 }
3131 return 0;
3132}
3133
3134// Warn on anti-patterns as the 'size' argument to strncat.
3135// The correct size argument should look like following:
3136// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3137void Sema::CheckStrncatArguments(const CallExpr *CE,
3138 IdentifierInfo *FnName) {
3139 // Don't crash if the user has the wrong number of arguments.
3140 if (CE->getNumArgs() < 3)
3141 return;
3142 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3143 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3144 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3145
3146 // Identify common expressions, which are wrongly used as the size argument
3147 // to strncat and may lead to buffer overflows.
3148 unsigned PatternType = 0;
3149 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3150 // - sizeof(dst)
3151 if (referToTheSameDecl(SizeOfArg, DstArg))
3152 PatternType = 1;
3153 // - sizeof(src)
3154 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3155 PatternType = 2;
3156 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3157 if (BE->getOpcode() == BO_Sub) {
3158 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3159 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3160 // - sizeof(dst) - strlen(dst)
3161 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3162 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3163 PatternType = 1;
3164 // - sizeof(src) - (anything)
3165 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3166 PatternType = 2;
3167 }
3168 }
3169
3170 if (PatternType == 0)
3171 return;
3172
Anna Zaksafdb0412012-02-03 01:27:37 +00003173 // Generate the diagnostic.
3174 SourceLocation SL = LenArg->getLocStart();
3175 SourceRange SR = LenArg->getSourceRange();
3176 SourceManager &SM = PP.getSourceManager();
3177
3178 // If the function is defined as a builtin macro, do not show macro expansion.
3179 if (SM.isMacroArgExpansion(SL)) {
3180 SL = SM.getSpellingLoc(SL);
3181 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3182 SM.getSpellingLoc(SR.getEnd()));
3183 }
3184
Anna Zaksc36bedc2012-02-01 19:08:57 +00003185 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003186 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003187 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003188 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003189
3190 // Output a FIXIT hint if the destination is an array (rather than a
3191 // pointer to an array). This could be enhanced to handle some
3192 // pointers if we know the actual size, like if DstArg is 'array+2'
3193 // we could say 'sizeof(array)-2'.
3194 QualType DstArgTy = DstArg->getType();
3195
3196 // Only handle constant-sized or VLAs, but not flexible members.
3197 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3198 // Only issue the FIXIT for arrays of size > 1.
3199 if (CAT->getSize().getSExtValue() <= 1)
3200 return;
3201 } else if (!DstArgTy->isVariableArrayType()) {
3202 return;
3203 }
3204
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003205 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003206 llvm::raw_svector_ostream OS(sizeString);
3207 OS << "sizeof(";
3208 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3209 OS << ") - ";
3210 OS << "strlen(";
3211 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3212 OS << ") - 1";
3213
Anna Zaksafdb0412012-02-03 01:27:37 +00003214 Diag(SL, diag::note_strncat_wrong_size)
3215 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003216}
3217
Ted Kremenek06de2762007-08-17 16:46:58 +00003218//===--- CHECK: Return Address of Stack Variable --------------------------===//
3219
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003220static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3221 Decl *ParentDecl);
3222static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3223 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003224
3225/// CheckReturnStackAddr - Check if a return statement returns the address
3226/// of a stack variable.
3227void
3228Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3229 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003231 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003232 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003233
3234 // Perform checking for returned stack addresses, local blocks,
3235 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003236 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003237 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003238 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003239 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003240 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003241 }
3242
3243 if (stackE == 0)
3244 return; // Nothing suspicious was found.
3245
3246 SourceLocation diagLoc;
3247 SourceRange diagRange;
3248 if (refVars.empty()) {
3249 diagLoc = stackE->getLocStart();
3250 diagRange = stackE->getSourceRange();
3251 } else {
3252 // We followed through a reference variable. 'stackE' contains the
3253 // problematic expression but we will warn at the return statement pointing
3254 // at the reference variable. We will later display the "trail" of
3255 // reference variables using notes.
3256 diagLoc = refVars[0]->getLocStart();
3257 diagRange = refVars[0]->getSourceRange();
3258 }
3259
3260 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3261 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3262 : diag::warn_ret_stack_addr)
3263 << DR->getDecl()->getDeclName() << diagRange;
3264 } else if (isa<BlockExpr>(stackE)) { // local block.
3265 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3266 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3267 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3268 } else { // local temporary.
3269 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3270 : diag::warn_ret_local_temp_addr)
3271 << diagRange;
3272 }
3273
3274 // Display the "trail" of reference variables that we followed until we
3275 // found the problematic expression using notes.
3276 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3277 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3278 // If this var binds to another reference var, show the range of the next
3279 // var, otherwise the var binds to the problematic expression, in which case
3280 // show the range of the expression.
3281 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3282 : stackE->getSourceRange();
3283 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3284 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003285 }
3286}
3287
3288/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3289/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003290/// to a location on the stack, a local block, an address of a label, or a
3291/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003292/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003293/// encounter a subexpression that (1) clearly does not lead to one of the
3294/// above problematic expressions (2) is something we cannot determine leads to
3295/// a problematic expression based on such local checking.
3296///
3297/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3298/// the expression that they point to. Such variables are added to the
3299/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003300///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003301/// EvalAddr processes expressions that are pointers that are used as
3302/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003303/// At the base case of the recursion is a check for the above problematic
3304/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003305///
3306/// This implementation handles:
3307///
3308/// * pointer-to-pointer casts
3309/// * implicit conversions from array references to pointers
3310/// * taking the address of fields
3311/// * arbitrary interplay between "&" and "*" operators
3312/// * pointer arithmetic from an address of a stack variable
3313/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003314static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3315 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003316 if (E->isTypeDependent())
3317 return NULL;
3318
Ted Kremenek06de2762007-08-17 16:46:58 +00003319 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003320 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003321 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003322 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003323 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Peter Collingbournef111d932011-04-15 00:35:48 +00003325 E = E->IgnoreParens();
3326
Ted Kremenek06de2762007-08-17 16:46:58 +00003327 // Our "symbolic interpreter" is just a dispatch off the currently
3328 // viewed AST node. We then recursively traverse the AST by calling
3329 // EvalAddr and EvalVal appropriately.
3330 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003331 case Stmt::DeclRefExprClass: {
3332 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3333
3334 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3335 // If this is a reference variable, follow through to the expression that
3336 // it points to.
3337 if (V->hasLocalStorage() &&
3338 V->getType()->isReferenceType() && V->hasInit()) {
3339 // Add the reference variable to the "trail".
3340 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003341 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003342 }
3343
3344 return NULL;
3345 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003346
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003347 case Stmt::UnaryOperatorClass: {
3348 // The only unary operator that make sense to handle here
3349 // is AddrOf. All others don't make sense as pointers.
3350 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003351
John McCall2de56d12010-08-25 11:45:40 +00003352 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003353 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003354 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003355 return NULL;
3356 }
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003358 case Stmt::BinaryOperatorClass: {
3359 // Handle pointer arithmetic. All other binary operators are not valid
3360 // in this context.
3361 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003362 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003363
John McCall2de56d12010-08-25 11:45:40 +00003364 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003365 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003367 Expr *Base = B->getLHS();
3368
3369 // Determine which argument is the real pointer base. It could be
3370 // the RHS argument instead of the LHS.
3371 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003373 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003374 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003375 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003376
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003377 // For conditional operators we need to see if either the LHS or RHS are
3378 // valid DeclRefExpr*s. If one of them is valid, we return it.
3379 case Stmt::ConditionalOperatorClass: {
3380 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003382 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003383 if (Expr *lhsExpr = C->getLHS()) {
3384 // In C++, we can have a throw-expression, which has 'void' type.
3385 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003386 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003387 return LHS;
3388 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003389
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003390 // In C++, we can have a throw-expression, which has 'void' type.
3391 if (C->getRHS()->getType()->isVoidType())
3392 return NULL;
3393
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003394 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003395 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003396
3397 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003398 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003399 return E; // local block.
3400 return NULL;
3401
3402 case Stmt::AddrLabelExprClass:
3403 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003404
John McCall80ee6e82011-11-10 05:35:25 +00003405 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003406 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3407 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003408
Ted Kremenek54b52742008-08-07 00:49:01 +00003409 // For casts, we need to handle conversions from arrays to
3410 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003411 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003412 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003413 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003414 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003415 case Stmt::CXXStaticCastExprClass:
3416 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003417 case Stmt::CXXConstCastExprClass:
3418 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003419 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3420 switch (cast<CastExpr>(E)->getCastKind()) {
3421 case CK_BitCast:
3422 case CK_LValueToRValue:
3423 case CK_NoOp:
3424 case CK_BaseToDerived:
3425 case CK_DerivedToBase:
3426 case CK_UncheckedDerivedToBase:
3427 case CK_Dynamic:
3428 case CK_CPointerToObjCPointerCast:
3429 case CK_BlockPointerToObjCPointerCast:
3430 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003431 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003432
3433 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003434 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003435
3436 default:
3437 return 0;
3438 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003439 }
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Douglas Gregor03e80032011-06-21 17:03:29 +00003441 case Stmt::MaterializeTemporaryExprClass:
3442 if (Expr *Result = EvalAddr(
3443 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003444 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003445 return Result;
3446
3447 return E;
3448
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003449 // Everything else: we simply don't reason about them.
3450 default:
3451 return NULL;
3452 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003453}
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Ted Kremenek06de2762007-08-17 16:46:58 +00003455
3456/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3457/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003458static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3459 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003460do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003461 // We should only be called for evaluating non-pointer expressions, or
3462 // expressions with a pointer type that are not used as references but instead
3463 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Ted Kremenek06de2762007-08-17 16:46:58 +00003465 // Our "symbolic interpreter" is just a dispatch off the currently
3466 // viewed AST node. We then recursively traverse the AST by calling
3467 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003468
3469 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003470 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003471 case Stmt::ImplicitCastExprClass: {
3472 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003473 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003474 E = IE->getSubExpr();
3475 continue;
3476 }
3477 return NULL;
3478 }
3479
John McCall80ee6e82011-11-10 05:35:25 +00003480 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003481 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003482
Douglas Gregora2813ce2009-10-23 18:54:35 +00003483 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003484 // When we hit a DeclRefExpr we are looking at code that refers to a
3485 // variable's name. If it's not a reference variable we check if it has
3486 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003487 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003489 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3490 // Check if it refers to itself, e.g. "int& i = i;".
3491 if (V == ParentDecl)
3492 return DR;
3493
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003494 if (V->hasLocalStorage()) {
3495 if (!V->getType()->isReferenceType())
3496 return DR;
3497
3498 // Reference variable, follow through to the expression that
3499 // it points to.
3500 if (V->hasInit()) {
3501 // Add the reference variable to the "trail".
3502 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003503 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003504 }
3505 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Ted Kremenek06de2762007-08-17 16:46:58 +00003508 return NULL;
3509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Ted Kremenek06de2762007-08-17 16:46:58 +00003511 case Stmt::UnaryOperatorClass: {
3512 // The only unary operator that make sense to handle here
3513 // is Deref. All others don't resolve to a "name." This includes
3514 // handling all sorts of rvalues passed to a unary operator.
3515 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003516
John McCall2de56d12010-08-25 11:45:40 +00003517 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003518 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003519
3520 return NULL;
3521 }
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Ted Kremenek06de2762007-08-17 16:46:58 +00003523 case Stmt::ArraySubscriptExprClass: {
3524 // Array subscripts are potential references to data on the stack. We
3525 // retrieve the DeclRefExpr* for the array variable if it indeed
3526 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003527 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003528 }
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Ted Kremenek06de2762007-08-17 16:46:58 +00003530 case Stmt::ConditionalOperatorClass: {
3531 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003532 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003533 ConditionalOperator *C = cast<ConditionalOperator>(E);
3534
Anders Carlsson39073232007-11-30 19:04:31 +00003535 // Handle the GNU extension for missing LHS.
3536 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003537 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003538 return LHS;
3539
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003540 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003541 }
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Ted Kremenek06de2762007-08-17 16:46:58 +00003543 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003544 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003545 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Ted Kremenek06de2762007-08-17 16:46:58 +00003547 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003548 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003549 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003550
3551 // Check whether the member type is itself a reference, in which case
3552 // we're not going to refer to the member, but to what the member refers to.
3553 if (M->getMemberDecl()->getType()->isReferenceType())
3554 return NULL;
3555
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003556 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003557 }
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Douglas Gregor03e80032011-06-21 17:03:29 +00003559 case Stmt::MaterializeTemporaryExprClass:
3560 if (Expr *Result = EvalVal(
3561 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003562 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003563 return Result;
3564
3565 return E;
3566
Ted Kremenek06de2762007-08-17 16:46:58 +00003567 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003568 // Check that we don't return or take the address of a reference to a
3569 // temporary. This is only useful in C++.
3570 if (!E->isTypeDependent() && E->isRValue())
3571 return E;
3572
3573 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003574 return NULL;
3575 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003576} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003577}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003578
3579//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3580
3581/// Check for comparisons of floating point operands using != and ==.
3582/// Issue a warning if these are no self-comparisons, as they are not likely
3583/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003584void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003585 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Richard Trieudd225092011-09-15 21:56:47 +00003587 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3588 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003589
3590 // Special case: check for x == x (which is OK).
3591 // Do not emit warnings for such cases.
3592 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3593 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3594 if (DRL->getDecl() == DRR->getDecl())
3595 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003596
3597
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003598 // Special case: check for comparisons against literals that can be exactly
3599 // represented by APFloat. In such cases, do not emit a warning. This
3600 // is a heuristic: often comparison against such literals are used to
3601 // detect if a value in a variable has not changed. This clearly can
3602 // lead to false negatives.
3603 if (EmitWarning) {
3604 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3605 if (FLL->isExact())
3606 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003607 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003608 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3609 if (FLR->isExact())
3610 EmitWarning = false;
3611 }
3612 }
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003614 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003615 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003616 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003617 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003618 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Sebastian Redl0eb23302009-01-19 00:08:26 +00003620 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003621 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003622 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003623 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003625 // Emit the diagnostic.
3626 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003627 Diag(Loc, diag::warn_floatingpoint_eq)
3628 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003629}
John McCallba26e582010-01-04 23:21:16 +00003630
John McCallf2370c92010-01-06 05:24:50 +00003631//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3632//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003633
John McCallf2370c92010-01-06 05:24:50 +00003634namespace {
John McCallba26e582010-01-04 23:21:16 +00003635
John McCallf2370c92010-01-06 05:24:50 +00003636/// Structure recording the 'active' range of an integer-valued
3637/// expression.
3638struct IntRange {
3639 /// The number of bits active in the int.
3640 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003641
John McCallf2370c92010-01-06 05:24:50 +00003642 /// True if the int is known not to have negative values.
3643 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003644
John McCallf2370c92010-01-06 05:24:50 +00003645 IntRange(unsigned Width, bool NonNegative)
3646 : Width(Width), NonNegative(NonNegative)
3647 {}
John McCallba26e582010-01-04 23:21:16 +00003648
John McCall1844a6e2010-11-10 23:38:19 +00003649 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003650 static IntRange forBoolType() {
3651 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003652 }
3653
John McCall1844a6e2010-11-10 23:38:19 +00003654 /// Returns the range of an opaque value of the given integral type.
3655 static IntRange forValueOfType(ASTContext &C, QualType T) {
3656 return forValueOfCanonicalType(C,
3657 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003658 }
3659
John McCall1844a6e2010-11-10 23:38:19 +00003660 /// Returns the range of an opaque value of a canonical integral type.
3661 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003662 assert(T->isCanonicalUnqualified());
3663
3664 if (const VectorType *VT = dyn_cast<VectorType>(T))
3665 T = VT->getElementType().getTypePtr();
3666 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3667 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003668
John McCall091f23f2010-11-09 22:22:12 +00003669 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003670 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3671 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003672 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003673 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3674
John McCall323ed742010-05-06 08:58:33 +00003675 unsigned NumPositive = Enum->getNumPositiveBits();
3676 unsigned NumNegative = Enum->getNumNegativeBits();
3677
3678 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3679 }
John McCallf2370c92010-01-06 05:24:50 +00003680
3681 const BuiltinType *BT = cast<BuiltinType>(T);
3682 assert(BT->isInteger());
3683
3684 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3685 }
3686
John McCall1844a6e2010-11-10 23:38:19 +00003687 /// Returns the "target" range of a canonical integral type, i.e.
3688 /// the range of values expressible in the type.
3689 ///
3690 /// This matches forValueOfCanonicalType except that enums have the
3691 /// full range of their type, not the range of their enumerators.
3692 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3693 assert(T->isCanonicalUnqualified());
3694
3695 if (const VectorType *VT = dyn_cast<VectorType>(T))
3696 T = VT->getElementType().getTypePtr();
3697 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3698 T = CT->getElementType().getTypePtr();
3699 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003700 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003701
3702 const BuiltinType *BT = cast<BuiltinType>(T);
3703 assert(BT->isInteger());
3704
3705 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3706 }
3707
3708 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003709 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003710 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003711 L.NonNegative && R.NonNegative);
3712 }
3713
John McCall1844a6e2010-11-10 23:38:19 +00003714 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003715 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003716 return IntRange(std::min(L.Width, R.Width),
3717 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003718 }
3719};
3720
Ted Kremenek0692a192012-01-31 05:37:37 +00003721static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3722 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003723 if (value.isSigned() && value.isNegative())
3724 return IntRange(value.getMinSignedBits(), false);
3725
3726 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003727 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003728
3729 // isNonNegative() just checks the sign bit without considering
3730 // signedness.
3731 return IntRange(value.getActiveBits(), true);
3732}
3733
Ted Kremenek0692a192012-01-31 05:37:37 +00003734static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3735 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003736 if (result.isInt())
3737 return GetValueRange(C, result.getInt(), MaxWidth);
3738
3739 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003740 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3741 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3742 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3743 R = IntRange::join(R, El);
3744 }
John McCallf2370c92010-01-06 05:24:50 +00003745 return R;
3746 }
3747
3748 if (result.isComplexInt()) {
3749 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3750 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3751 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003752 }
3753
3754 // This can happen with lossless casts to intptr_t of "based" lvalues.
3755 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003756 // FIXME: The only reason we need to pass the type in here is to get
3757 // the sign right on this one case. It would be nice if APValue
3758 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003759 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003760 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003761}
John McCallf2370c92010-01-06 05:24:50 +00003762
3763/// Pseudo-evaluate the given integer expression, estimating the
3764/// range of values it might take.
3765///
3766/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003767static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003768 E = E->IgnoreParens();
3769
3770 // Try a full evaluation first.
3771 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003772 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003773 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003774
3775 // I think we only want to look through implicit casts here; if the
3776 // user has an explicit widening cast, we should treat the value as
3777 // being of the new, wider type.
3778 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003779 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003780 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3781
John McCall1844a6e2010-11-10 23:38:19 +00003782 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003783
John McCall2de56d12010-08-25 11:45:40 +00003784 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003785
John McCallf2370c92010-01-06 05:24:50 +00003786 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003787 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003788 return OutputTypeRange;
3789
3790 IntRange SubRange
3791 = GetExprRange(C, CE->getSubExpr(),
3792 std::min(MaxWidth, OutputTypeRange.Width));
3793
3794 // Bail out if the subexpr's range is as wide as the cast type.
3795 if (SubRange.Width >= OutputTypeRange.Width)
3796 return OutputTypeRange;
3797
3798 // Otherwise, we take the smaller width, and we're non-negative if
3799 // either the output type or the subexpr is.
3800 return IntRange(SubRange.Width,
3801 SubRange.NonNegative || OutputTypeRange.NonNegative);
3802 }
3803
3804 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3805 // If we can fold the condition, just take that operand.
3806 bool CondResult;
3807 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3808 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3809 : CO->getFalseExpr(),
3810 MaxWidth);
3811
3812 // Otherwise, conservatively merge.
3813 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3814 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3815 return IntRange::join(L, R);
3816 }
3817
3818 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3819 switch (BO->getOpcode()) {
3820
3821 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003822 case BO_LAnd:
3823 case BO_LOr:
3824 case BO_LT:
3825 case BO_GT:
3826 case BO_LE:
3827 case BO_GE:
3828 case BO_EQ:
3829 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003830 return IntRange::forBoolType();
3831
John McCall862ff872011-07-13 06:35:24 +00003832 // The type of the assignments is the type of the LHS, so the RHS
3833 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003834 case BO_MulAssign:
3835 case BO_DivAssign:
3836 case BO_RemAssign:
3837 case BO_AddAssign:
3838 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003839 case BO_XorAssign:
3840 case BO_OrAssign:
3841 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003842 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003843
John McCall862ff872011-07-13 06:35:24 +00003844 // Simple assignments just pass through the RHS, which will have
3845 // been coerced to the LHS type.
3846 case BO_Assign:
3847 // TODO: bitfields?
3848 return GetExprRange(C, BO->getRHS(), MaxWidth);
3849
John McCallf2370c92010-01-06 05:24:50 +00003850 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003851 case BO_PtrMemD:
3852 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003853 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003854
John McCall60fad452010-01-06 22:07:33 +00003855 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003856 case BO_And:
3857 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003858 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3859 GetExprRange(C, BO->getRHS(), MaxWidth));
3860
John McCallf2370c92010-01-06 05:24:50 +00003861 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003862 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003863 // ...except that we want to treat '1 << (blah)' as logically
3864 // positive. It's an important idiom.
3865 if (IntegerLiteral *I
3866 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3867 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003868 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003869 return IntRange(R.Width, /*NonNegative*/ true);
3870 }
3871 }
3872 // fallthrough
3873
John McCall2de56d12010-08-25 11:45:40 +00003874 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003875 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003876
John McCall60fad452010-01-06 22:07:33 +00003877 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003878 case BO_Shr:
3879 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003880 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3881
3882 // If the shift amount is a positive constant, drop the width by
3883 // that much.
3884 llvm::APSInt shift;
3885 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3886 shift.isNonNegative()) {
3887 unsigned zext = shift.getZExtValue();
3888 if (zext >= L.Width)
3889 L.Width = (L.NonNegative ? 0 : 1);
3890 else
3891 L.Width -= zext;
3892 }
3893
3894 return L;
3895 }
3896
3897 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003898 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003899 return GetExprRange(C, BO->getRHS(), MaxWidth);
3900
John McCall60fad452010-01-06 22:07:33 +00003901 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003902 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003903 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003904 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003905 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003906
John McCall00fe7612011-07-14 22:39:48 +00003907 // The width of a division result is mostly determined by the size
3908 // of the LHS.
3909 case BO_Div: {
3910 // Don't 'pre-truncate' the operands.
3911 unsigned opWidth = C.getIntWidth(E->getType());
3912 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3913
3914 // If the divisor is constant, use that.
3915 llvm::APSInt divisor;
3916 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3917 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3918 if (log2 >= L.Width)
3919 L.Width = (L.NonNegative ? 0 : 1);
3920 else
3921 L.Width = std::min(L.Width - log2, MaxWidth);
3922 return L;
3923 }
3924
3925 // Otherwise, just use the LHS's width.
3926 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3927 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3928 }
3929
3930 // The result of a remainder can't be larger than the result of
3931 // either side.
3932 case BO_Rem: {
3933 // Don't 'pre-truncate' the operands.
3934 unsigned opWidth = C.getIntWidth(E->getType());
3935 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3936 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3937
3938 IntRange meet = IntRange::meet(L, R);
3939 meet.Width = std::min(meet.Width, MaxWidth);
3940 return meet;
3941 }
3942
3943 // The default behavior is okay for these.
3944 case BO_Mul:
3945 case BO_Add:
3946 case BO_Xor:
3947 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003948 break;
3949 }
3950
John McCall00fe7612011-07-14 22:39:48 +00003951 // The default case is to treat the operation as if it were closed
3952 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003953 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3954 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3955 return IntRange::join(L, R);
3956 }
3957
3958 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3959 switch (UO->getOpcode()) {
3960 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003961 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003962 return IntRange::forBoolType();
3963
3964 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003965 case UO_Deref:
3966 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003967 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003968
3969 default:
3970 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3971 }
3972 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003973
3974 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003975 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003976 }
John McCallf2370c92010-01-06 05:24:50 +00003977
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003978 if (FieldDecl *BitField = E->getBitField())
3979 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003980 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003981
John McCall1844a6e2010-11-10 23:38:19 +00003982 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003983}
John McCall51313c32010-01-04 23:31:57 +00003984
Ted Kremenek0692a192012-01-31 05:37:37 +00003985static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003986 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3987}
3988
John McCall51313c32010-01-04 23:31:57 +00003989/// Checks whether the given value, which currently has the given
3990/// source semantics, has the same value when coerced through the
3991/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003992static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3993 const llvm::fltSemantics &Src,
3994 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003995 llvm::APFloat truncated = value;
3996
3997 bool ignored;
3998 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3999 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4000
4001 return truncated.bitwiseIsEqual(value);
4002}
4003
4004/// Checks whether the given value, which currently has the given
4005/// source semantics, has the same value when coerced through the
4006/// target semantics.
4007///
4008/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004009static bool IsSameFloatAfterCast(const APValue &value,
4010 const llvm::fltSemantics &Src,
4011 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004012 if (value.isFloat())
4013 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4014
4015 if (value.isVector()) {
4016 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4017 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4018 return false;
4019 return true;
4020 }
4021
4022 assert(value.isComplexFloat());
4023 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4024 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4025}
4026
Ted Kremenek0692a192012-01-31 05:37:37 +00004027static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004028
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004029static bool IsZero(Sema &S, Expr *E) {
4030 // Suppress cases where we are comparing against an enum constant.
4031 if (const DeclRefExpr *DR =
4032 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4033 if (isa<EnumConstantDecl>(DR->getDecl()))
4034 return false;
4035
4036 // Suppress cases where the '0' value is expanded from a macro.
4037 if (E->getLocStart().isMacroID())
4038 return false;
4039
John McCall323ed742010-05-06 08:58:33 +00004040 llvm::APSInt Value;
4041 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4042}
4043
John McCall372e1032010-10-06 00:25:24 +00004044static bool HasEnumType(Expr *E) {
4045 // Strip off implicit integral promotions.
4046 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004047 if (ICE->getCastKind() != CK_IntegralCast &&
4048 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004049 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004050 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004051 }
4052
4053 return E->getType()->isEnumeralType();
4054}
4055
Ted Kremenek0692a192012-01-31 05:37:37 +00004056static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004057 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004058 if (E->isValueDependent())
4059 return;
4060
John McCall2de56d12010-08-25 11:45:40 +00004061 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004062 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004063 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004064 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004065 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004066 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004067 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004068 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004069 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004070 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004071 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004072 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004073 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004074 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004075 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004076 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4077 }
4078}
4079
4080/// Analyze the operands of the given comparison. Implements the
4081/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004082static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004083 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4084 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004085}
John McCall51313c32010-01-04 23:31:57 +00004086
John McCallba26e582010-01-04 23:21:16 +00004087/// \brief Implements -Wsign-compare.
4088///
Richard Trieudd225092011-09-15 21:56:47 +00004089/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004090static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004091 // The type the comparison is being performed in.
4092 QualType T = E->getLHS()->getType();
4093 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4094 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004095
John McCall323ed742010-05-06 08:58:33 +00004096 // We don't do anything special if this isn't an unsigned integral
4097 // comparison: we're only interested in integral comparisons, and
4098 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004099 //
4100 // We also don't care about value-dependent expressions or expressions
4101 // whose result is a constant.
4102 if (!T->hasUnsignedIntegerRepresentation()
4103 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004104 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004105
Richard Trieudd225092011-09-15 21:56:47 +00004106 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4107 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004108
John McCall323ed742010-05-06 08:58:33 +00004109 // Check to see if one of the (unmodified) operands is of different
4110 // signedness.
4111 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004112 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4113 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004114 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004115 signedOperand = LHS;
4116 unsignedOperand = RHS;
4117 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4118 signedOperand = RHS;
4119 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004120 } else {
John McCall323ed742010-05-06 08:58:33 +00004121 CheckTrivialUnsignedComparison(S, E);
4122 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004123 }
4124
John McCall323ed742010-05-06 08:58:33 +00004125 // Otherwise, calculate the effective range of the signed operand.
4126 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004127
John McCall323ed742010-05-06 08:58:33 +00004128 // Go ahead and analyze implicit conversions in the operands. Note
4129 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004130 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4131 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004132
John McCall323ed742010-05-06 08:58:33 +00004133 // If the signed range is non-negative, -Wsign-compare won't fire,
4134 // but we should still check for comparisons which are always true
4135 // or false.
4136 if (signedRange.NonNegative)
4137 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004138
4139 // For (in)equality comparisons, if the unsigned operand is a
4140 // constant which cannot collide with a overflowed signed operand,
4141 // then reinterpreting the signed operand as unsigned will not
4142 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004143 if (E->isEqualityOp()) {
4144 unsigned comparisonWidth = S.Context.getIntWidth(T);
4145 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004146
John McCall323ed742010-05-06 08:58:33 +00004147 // We should never be unable to prove that the unsigned operand is
4148 // non-negative.
4149 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4150
4151 if (unsignedRange.Width < comparisonWidth)
4152 return;
4153 }
4154
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004155 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4156 S.PDiag(diag::warn_mixed_sign_comparison)
4157 << LHS->getType() << RHS->getType()
4158 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004159}
4160
John McCall15d7d122010-11-11 03:21:53 +00004161/// Analyzes an attempt to assign the given value to a bitfield.
4162///
4163/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004164static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4165 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004166 assert(Bitfield->isBitField());
4167 if (Bitfield->isInvalidDecl())
4168 return false;
4169
John McCall91b60142010-11-11 05:33:51 +00004170 // White-list bool bitfields.
4171 if (Bitfield->getType()->isBooleanType())
4172 return false;
4173
Douglas Gregor46ff3032011-02-04 13:09:01 +00004174 // Ignore value- or type-dependent expressions.
4175 if (Bitfield->getBitWidth()->isValueDependent() ||
4176 Bitfield->getBitWidth()->isTypeDependent() ||
4177 Init->isValueDependent() ||
4178 Init->isTypeDependent())
4179 return false;
4180
John McCall15d7d122010-11-11 03:21:53 +00004181 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4182
Richard Smith80d4b552011-12-28 19:48:30 +00004183 llvm::APSInt Value;
4184 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004185 return false;
4186
John McCall15d7d122010-11-11 03:21:53 +00004187 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004188 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004189
4190 if (OriginalWidth <= FieldWidth)
4191 return false;
4192
Eli Friedman3a643af2012-01-26 23:11:39 +00004193 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004194 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004195 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004196
Eli Friedman3a643af2012-01-26 23:11:39 +00004197 // Check whether the stored value is equal to the original value.
4198 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004199 if (Value == TruncatedValue)
4200 return false;
4201
Eli Friedman3a643af2012-01-26 23:11:39 +00004202 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004203 // therefore don't strictly fit into a signed bitfield of width 1.
4204 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004205 return false;
4206
John McCall15d7d122010-11-11 03:21:53 +00004207 std::string PrettyValue = Value.toString(10);
4208 std::string PrettyTrunc = TruncatedValue.toString(10);
4209
4210 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4211 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4212 << Init->getSourceRange();
4213
4214 return true;
4215}
4216
John McCallbeb22aa2010-11-09 23:24:47 +00004217/// Analyze the given simple or compound assignment for warning-worthy
4218/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004219static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004220 // Just recurse on the LHS.
4221 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4222
4223 // We want to recurse on the RHS as normal unless we're assigning to
4224 // a bitfield.
4225 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004226 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4227 E->getOperatorLoc())) {
4228 // Recurse, ignoring any implicit conversions on the RHS.
4229 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4230 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004231 }
4232 }
4233
4234 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4235}
4236
John McCall51313c32010-01-04 23:31:57 +00004237/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004238static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004239 SourceLocation CContext, unsigned diag,
4240 bool pruneControlFlow = false) {
4241 if (pruneControlFlow) {
4242 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4243 S.PDiag(diag)
4244 << SourceType << T << E->getSourceRange()
4245 << SourceRange(CContext));
4246 return;
4247 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004248 S.Diag(E->getExprLoc(), diag)
4249 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4250}
4251
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004252/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004253static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004254 SourceLocation CContext, unsigned diag,
4255 bool pruneControlFlow = false) {
4256 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004257}
4258
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004259/// Diagnose an implicit cast from a literal expression. Does not warn when the
4260/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004261void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4262 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004263 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004264 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004265 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004266 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4267 T->hasUnsignedIntegerRepresentation());
4268 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004269 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004270 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004271 return;
4272
David Blaikiebe0ee872012-05-15 16:56:36 +00004273 SmallString<16> PrettySourceValue;
4274 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004275 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004276 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4277 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4278 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004279 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004280
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004281 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004282 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4283 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004284}
4285
John McCall091f23f2010-11-09 22:22:12 +00004286std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4287 if (!Range.Width) return "0";
4288
4289 llvm::APSInt ValueInRange = Value;
4290 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004291 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004292 return ValueInRange.toString(10);
4293}
4294
John McCall323ed742010-05-06 08:58:33 +00004295void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004296 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004297 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004298
John McCall323ed742010-05-06 08:58:33 +00004299 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4300 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4301 if (Source == Target) return;
4302 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004303
Chandler Carruth108f7562011-07-26 05:40:03 +00004304 // If the conversion context location is invalid don't complain. We also
4305 // don't want to emit a warning if the issue occurs from the expansion of
4306 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4307 // delay this check as long as possible. Once we detect we are in that
4308 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004309 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004310 return;
4311
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004312 // Diagnose implicit casts to bool.
4313 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4314 if (isa<StringLiteral>(E))
4315 // Warn on string literal to bool. Checks for string literals in logical
4316 // expressions, for instances, assert(0 && "error here"), is prevented
4317 // by a check in AnalyzeImplicitConversions().
4318 return DiagnoseImpCast(S, E, T, CC,
4319 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004320 if (Source->isFunctionType()) {
4321 // Warn on function to bool. Checks free functions and static member
4322 // functions. Weakly imported functions are excluded from the check,
4323 // since it's common to test their value to check whether the linker
4324 // found a definition for them.
4325 ValueDecl *D = 0;
4326 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4327 D = R->getDecl();
4328 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4329 D = M->getMemberDecl();
4330 }
4331
4332 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004333 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4334 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4335 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004336 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4337 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4338 QualType ReturnType;
4339 UnresolvedSet<4> NonTemplateOverloads;
4340 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4341 if (!ReturnType.isNull()
4342 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4343 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4344 << FixItHint::CreateInsertion(
4345 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004346 return;
4347 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004348 }
4349 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004350 }
John McCall51313c32010-01-04 23:31:57 +00004351
4352 // Strip vector types.
4353 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004354 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004355 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004356 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004357 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004358 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004359
4360 // If the vector cast is cast between two vectors of the same size, it is
4361 // a bitcast, not a conversion.
4362 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4363 return;
John McCall51313c32010-01-04 23:31:57 +00004364
4365 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4366 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4367 }
4368
4369 // Strip complex types.
4370 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004371 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004372 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004373 return;
4374
John McCallb4eb64d2010-10-08 02:01:28 +00004375 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004376 }
John McCall51313c32010-01-04 23:31:57 +00004377
4378 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4379 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4380 }
4381
4382 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4383 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4384
4385 // If the source is floating point...
4386 if (SourceBT && SourceBT->isFloatingPoint()) {
4387 // ...and the target is floating point...
4388 if (TargetBT && TargetBT->isFloatingPoint()) {
4389 // ...then warn if we're dropping FP rank.
4390
4391 // Builtin FP kinds are ordered by increasing FP rank.
4392 if (SourceBT->getKind() > TargetBT->getKind()) {
4393 // Don't warn about float constants that are precisely
4394 // representable in the target type.
4395 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004396 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004397 // Value might be a float, a float vector, or a float complex.
4398 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004399 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4400 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004401 return;
4402 }
4403
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004404 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004405 return;
4406
John McCallb4eb64d2010-10-08 02:01:28 +00004407 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004408 }
4409 return;
4410 }
4411
Ted Kremenekef9ff882011-03-10 20:03:42 +00004412 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004413 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004414 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004415 return;
4416
Chandler Carrutha5b93322011-02-17 11:05:49 +00004417 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004418 // We also want to warn on, e.g., "int i = -1.234"
4419 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4420 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4421 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4422
Chandler Carruthf65076e2011-04-10 08:36:24 +00004423 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4424 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004425 } else {
4426 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4427 }
4428 }
John McCall51313c32010-01-04 23:31:57 +00004429
4430 return;
4431 }
4432
Richard Trieu1838ca52011-05-29 19:59:02 +00004433 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004434 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004435 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004436 SourceLocation Loc = E->getSourceRange().getBegin();
4437 if (Loc.isMacroID())
4438 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004439 if (!Loc.isMacroID() || CC.isMacroID())
4440 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4441 << T << clang::SourceRange(CC)
4442 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004443 }
4444
David Blaikieb26331b2012-06-19 21:19:06 +00004445 if (!Source->isIntegerType() || !Target->isIntegerType())
4446 return;
4447
David Blaikiebe0ee872012-05-15 16:56:36 +00004448 // TODO: remove this early return once the false positives for constant->bool
4449 // in templates, macros, etc, are reduced or removed.
4450 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4451 return;
4452
John McCall323ed742010-05-06 08:58:33 +00004453 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004454 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004455
4456 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004457 // If the source is a constant, use a default-on diagnostic.
4458 // TODO: this should happen for bitfield stores, too.
4459 llvm::APSInt Value(32);
4460 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004461 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004462 return;
4463
John McCall091f23f2010-11-09 22:22:12 +00004464 std::string PrettySourceValue = Value.toString(10);
4465 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4466
Ted Kremenek5e745da2011-10-22 02:37:33 +00004467 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4468 S.PDiag(diag::warn_impcast_integer_precision_constant)
4469 << PrettySourceValue << PrettyTargetValue
4470 << E->getType() << T << E->getSourceRange()
4471 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004472 return;
4473 }
4474
Chris Lattnerb792b302011-06-14 04:51:15 +00004475 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004476 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004477 return;
4478
David Blaikie37050842012-04-12 22:40:54 +00004479 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004480 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4481 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004482 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004483 }
4484
4485 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4486 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4487 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004488
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004489 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004490 return;
4491
John McCall323ed742010-05-06 08:58:33 +00004492 unsigned DiagID = diag::warn_impcast_integer_sign;
4493
4494 // Traditionally, gcc has warned about this under -Wsign-compare.
4495 // We also want to warn about it in -Wconversion.
4496 // So if -Wconversion is off, use a completely identical diagnostic
4497 // in the sign-compare group.
4498 // The conditional-checking code will
4499 if (ICContext) {
4500 DiagID = diag::warn_impcast_integer_sign_conditional;
4501 *ICContext = true;
4502 }
4503
John McCallb4eb64d2010-10-08 02:01:28 +00004504 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004505 }
4506
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004507 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004508 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4509 // type, to give us better diagnostics.
4510 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004511 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004512 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4513 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4514 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4515 SourceType = S.Context.getTypeDeclType(Enum);
4516 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4517 }
4518 }
4519
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004520 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4521 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4522 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004523 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004524 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004525 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004526 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004527 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004528 return;
4529
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004530 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004531 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004532 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004533
John McCall51313c32010-01-04 23:31:57 +00004534 return;
4535}
4536
David Blaikie9fb1ac52012-05-15 21:57:38 +00004537void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4538 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004539
4540void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004541 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004542 E = E->IgnoreParenImpCasts();
4543
4544 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004545 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004546
John McCallb4eb64d2010-10-08 02:01:28 +00004547 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004548 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004549 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004550 return;
4551}
4552
David Blaikie9fb1ac52012-05-15 21:57:38 +00004553void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4554 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004555 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004556
4557 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004558 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4559 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004560
4561 // If -Wconversion would have warned about either of the candidates
4562 // for a signedness conversion to the context type...
4563 if (!Suspicious) return;
4564
4565 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004566 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4567 CC))
John McCall323ed742010-05-06 08:58:33 +00004568 return;
4569
John McCall323ed742010-05-06 08:58:33 +00004570 // ...then check whether it would have warned about either of the
4571 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004572 if (E->getType() == T) return;
4573
4574 Suspicious = false;
4575 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4576 E->getType(), CC, &Suspicious);
4577 if (!Suspicious)
4578 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004579 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004580}
4581
4582/// AnalyzeImplicitConversions - Find and report any interesting
4583/// implicit conversions in the given expression. There are a couple
4584/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004585void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004586 QualType T = OrigE->getType();
4587 Expr *E = OrigE->IgnoreParenImpCasts();
4588
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004589 if (E->isTypeDependent() || E->isValueDependent())
4590 return;
4591
John McCall323ed742010-05-06 08:58:33 +00004592 // For conditional operators, we analyze the arguments as if they
4593 // were being fed directly into the output.
4594 if (isa<ConditionalOperator>(E)) {
4595 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004596 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004597 return;
4598 }
4599
4600 // Go ahead and check any implicit conversions we might have skipped.
4601 // The non-canonical typecheck is just an optimization;
4602 // CheckImplicitConversion will filter out dead implicit conversions.
4603 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004604 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004605
4606 // Now continue drilling into this expression.
4607
4608 // Skip past explicit casts.
4609 if (isa<ExplicitCastExpr>(E)) {
4610 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004611 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004612 }
4613
John McCallbeb22aa2010-11-09 23:24:47 +00004614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4615 // Do a somewhat different check with comparison operators.
4616 if (BO->isComparisonOp())
4617 return AnalyzeComparison(S, BO);
4618
Eli Friedman0fa06382012-01-26 23:34:06 +00004619 // And with simple assignments.
4620 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004621 return AnalyzeAssignment(S, BO);
4622 }
John McCall323ed742010-05-06 08:58:33 +00004623
4624 // These break the otherwise-useful invariant below. Fortunately,
4625 // we don't really need to recurse into them, because any internal
4626 // expressions should have been analyzed already when they were
4627 // built into statements.
4628 if (isa<StmtExpr>(E)) return;
4629
4630 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004631 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004632
4633 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004634 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004635 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4636 bool IsLogicalOperator = BO && BO->isLogicalOp();
4637 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004638 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004639 if (!ChildExpr)
4640 continue;
4641
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004642 if (IsLogicalOperator &&
4643 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4644 // Ignore checking string literals that are in logical operators.
4645 continue;
4646 AnalyzeImplicitConversions(S, ChildExpr, CC);
4647 }
John McCall323ed742010-05-06 08:58:33 +00004648}
4649
4650} // end anonymous namespace
4651
4652/// Diagnoses "dangerous" implicit conversions within the given
4653/// expression (which is a full expression). Implements -Wconversion
4654/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004655///
4656/// \param CC the "context" location of the implicit conversion, i.e.
4657/// the most location of the syntactic entity requiring the implicit
4658/// conversion
4659void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004660 // Don't diagnose in unevaluated contexts.
4661 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4662 return;
4663
4664 // Don't diagnose for value- or type-dependent expressions.
4665 if (E->isTypeDependent() || E->isValueDependent())
4666 return;
4667
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004668 // Check for array bounds violations in cases where the check isn't triggered
4669 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4670 // ArraySubscriptExpr is on the RHS of a variable initialization.
4671 CheckArrayAccess(E);
4672
John McCallb4eb64d2010-10-08 02:01:28 +00004673 // This is not the right CC for (e.g.) a variable initialization.
4674 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004675}
4676
John McCall15d7d122010-11-11 03:21:53 +00004677void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4678 FieldDecl *BitField,
4679 Expr *Init) {
4680 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4681}
4682
Mike Stumpf8c49212010-01-21 03:59:47 +00004683/// CheckParmsForFunctionDef - Check that the parameters of the given
4684/// function are appropriate for the definition of a function. This
4685/// takes care of any checks that cannot be performed on the
4686/// declaration itself, e.g., that the types of each of the function
4687/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004688bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4689 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004690 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004691 for (; P != PEnd; ++P) {
4692 ParmVarDecl *Param = *P;
4693
Mike Stumpf8c49212010-01-21 03:59:47 +00004694 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4695 // function declarator that is part of a function definition of
4696 // that function shall not have incomplete type.
4697 //
4698 // This is also C++ [dcl.fct]p6.
4699 if (!Param->isInvalidDecl() &&
4700 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004701 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004702 Param->setInvalidDecl();
4703 HasInvalidParm = true;
4704 }
4705
4706 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4707 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004708 if (CheckParameterNames &&
4709 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004710 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004711 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004712 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004713
4714 // C99 6.7.5.3p12:
4715 // If the function declarator is not part of a definition of that
4716 // function, parameters may have incomplete type and may use the [*]
4717 // notation in their sequences of declarator specifiers to specify
4718 // variable length array types.
4719 QualType PType = Param->getOriginalType();
4720 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4721 if (AT->getSizeModifier() == ArrayType::Star) {
4722 // FIXME: This diagnosic should point the the '[*]' if source-location
4723 // information is added for it.
4724 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4725 }
4726 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004727 }
4728
4729 return HasInvalidParm;
4730}
John McCallb7f4ffe2010-08-12 21:44:57 +00004731
4732/// CheckCastAlign - Implements -Wcast-align, which warns when a
4733/// pointer cast increases the alignment requirements.
4734void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4735 // This is actually a lot of work to potentially be doing on every
4736 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004737 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4738 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004739 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004740 return;
4741
4742 // Ignore dependent types.
4743 if (T->isDependentType() || Op->getType()->isDependentType())
4744 return;
4745
4746 // Require that the destination be a pointer type.
4747 const PointerType *DestPtr = T->getAs<PointerType>();
4748 if (!DestPtr) return;
4749
4750 // If the destination has alignment 1, we're done.
4751 QualType DestPointee = DestPtr->getPointeeType();
4752 if (DestPointee->isIncompleteType()) return;
4753 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4754 if (DestAlign.isOne()) return;
4755
4756 // Require that the source be a pointer type.
4757 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4758 if (!SrcPtr) return;
4759 QualType SrcPointee = SrcPtr->getPointeeType();
4760
4761 // Whitelist casts from cv void*. We already implicitly
4762 // whitelisted casts to cv void*, since they have alignment 1.
4763 // Also whitelist casts involving incomplete types, which implicitly
4764 // includes 'void'.
4765 if (SrcPointee->isIncompleteType()) return;
4766
4767 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4768 if (SrcAlign >= DestAlign) return;
4769
4770 Diag(TRange.getBegin(), diag::warn_cast_align)
4771 << Op->getType() << T
4772 << static_cast<unsigned>(SrcAlign.getQuantity())
4773 << static_cast<unsigned>(DestAlign.getQuantity())
4774 << TRange << Op->getSourceRange();
4775}
4776
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004777static const Type* getElementType(const Expr *BaseExpr) {
4778 const Type* EltType = BaseExpr->getType().getTypePtr();
4779 if (EltType->isAnyPointerType())
4780 return EltType->getPointeeType().getTypePtr();
4781 else if (EltType->isArrayType())
4782 return EltType->getBaseElementTypeUnsafe();
4783 return EltType;
4784}
4785
Chandler Carruthc2684342011-08-05 09:10:50 +00004786/// \brief Check whether this array fits the idiom of a size-one tail padded
4787/// array member of a struct.
4788///
4789/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4790/// commonly used to emulate flexible arrays in C89 code.
4791static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4792 const NamedDecl *ND) {
4793 if (Size != 1 || !ND) return false;
4794
4795 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4796 if (!FD) return false;
4797
4798 // Don't consider sizes resulting from macro expansions or template argument
4799 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004800
4801 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004802 while (TInfo) {
4803 TypeLoc TL = TInfo->getTypeLoc();
4804 // Look through typedefs.
4805 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4806 if (TTL) {
4807 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4808 TInfo = TDL->getTypeSourceInfo();
4809 continue;
4810 }
4811 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4812 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004813 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4814 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004815 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004816 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004817
4818 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004819 if (!RD) return false;
4820 if (RD->isUnion()) return false;
4821 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4822 if (!CRD->isStandardLayout()) return false;
4823 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004824
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004825 // See if this is the last field decl in the record.
4826 const Decl *D = FD;
4827 while ((D = D->getNextDeclInContext()))
4828 if (isa<FieldDecl>(D))
4829 return false;
4830 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004831}
4832
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004833void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004834 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004835 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004836 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004837 if (IndexExpr->isValueDependent())
4838 return;
4839
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004840 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004841 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004842 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004843 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004844 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004845 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004846
Chandler Carruth34064582011-02-17 20:55:08 +00004847 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004848 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004849 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004850 if (IndexNegated)
4851 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004852
Chandler Carruthba447122011-08-05 08:07:29 +00004853 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004854 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4855 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004856 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004857 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004858
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004859 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004860 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004861 if (!size.isStrictlyPositive())
4862 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004863
4864 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004865 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004866 // Make sure we're comparing apples to apples when comparing index to size
4867 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4868 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004869 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004870 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004871 if (ptrarith_typesize != array_typesize) {
4872 // There's a cast to a different size type involved
4873 uint64_t ratio = array_typesize / ptrarith_typesize;
4874 // TODO: Be smarter about handling cases where array_typesize is not a
4875 // multiple of ptrarith_typesize
4876 if (ptrarith_typesize * ratio == array_typesize)
4877 size *= llvm::APInt(size.getBitWidth(), ratio);
4878 }
4879 }
4880
Chandler Carruth34064582011-02-17 20:55:08 +00004881 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004882 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004883 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004884 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004885
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004886 // For array subscripting the index must be less than size, but for pointer
4887 // arithmetic also allow the index (offset) to be equal to size since
4888 // computing the next address after the end of the array is legal and
4889 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004890 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004891 return;
4892
4893 // Also don't warn for arrays of size 1 which are members of some
4894 // structure. These are often used to approximate flexible arrays in C89
4895 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004896 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004897 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004898
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004899 // Suppress the warning if the subscript expression (as identified by the
4900 // ']' location) and the index expression are both from macro expansions
4901 // within a system header.
4902 if (ASE) {
4903 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4904 ASE->getRBracketLoc());
4905 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4906 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4907 IndexExpr->getLocStart());
4908 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4909 return;
4910 }
4911 }
4912
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004913 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004914 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004915 DiagID = diag::warn_array_index_exceeds_bounds;
4916
4917 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4918 PDiag(DiagID) << index.toString(10, true)
4919 << size.toString(10, true)
4920 << (unsigned)size.getLimitedValue(~0U)
4921 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004922 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004923 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004924 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004925 DiagID = diag::warn_ptr_arith_precedes_bounds;
4926 if (index.isNegative()) index = -index;
4927 }
4928
4929 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4930 PDiag(DiagID) << index.toString(10, true)
4931 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004932 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004933
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004934 if (!ND) {
4935 // Try harder to find a NamedDecl to point at in the note.
4936 while (const ArraySubscriptExpr *ASE =
4937 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4938 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4939 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4940 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4941 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4942 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4943 }
4944
Chandler Carruth35001ca2011-02-17 21:10:52 +00004945 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004946 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4947 PDiag(diag::note_array_index_out_of_bounds)
4948 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004949}
4950
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004951void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004952 int AllowOnePastEnd = 0;
4953 while (expr) {
4954 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004955 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004956 case Stmt::ArraySubscriptExprClass: {
4957 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004958 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004959 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004960 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004961 }
4962 case Stmt::UnaryOperatorClass: {
4963 // Only unwrap the * and & unary operators
4964 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4965 expr = UO->getSubExpr();
4966 switch (UO->getOpcode()) {
4967 case UO_AddrOf:
4968 AllowOnePastEnd++;
4969 break;
4970 case UO_Deref:
4971 AllowOnePastEnd--;
4972 break;
4973 default:
4974 return;
4975 }
4976 break;
4977 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004978 case Stmt::ConditionalOperatorClass: {
4979 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4980 if (const Expr *lhs = cond->getLHS())
4981 CheckArrayAccess(lhs);
4982 if (const Expr *rhs = cond->getRHS())
4983 CheckArrayAccess(rhs);
4984 return;
4985 }
4986 default:
4987 return;
4988 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004989 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004990}
John McCallf85e1932011-06-15 23:02:42 +00004991
4992//===--- CHECK: Objective-C retain cycles ----------------------------------//
4993
4994namespace {
4995 struct RetainCycleOwner {
4996 RetainCycleOwner() : Variable(0), Indirect(false) {}
4997 VarDecl *Variable;
4998 SourceRange Range;
4999 SourceLocation Loc;
5000 bool Indirect;
5001
5002 void setLocsFrom(Expr *e) {
5003 Loc = e->getExprLoc();
5004 Range = e->getSourceRange();
5005 }
5006 };
5007}
5008
5009/// Consider whether capturing the given variable can possibly lead to
5010/// a retain cycle.
5011static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5012 // In ARC, it's captured strongly iff the variable has __strong
5013 // lifetime. In MRR, it's captured strongly if the variable is
5014 // __block and has an appropriate type.
5015 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5016 return false;
5017
5018 owner.Variable = var;
5019 owner.setLocsFrom(ref);
5020 return true;
5021}
5022
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005023static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005024 while (true) {
5025 e = e->IgnoreParens();
5026 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5027 switch (cast->getCastKind()) {
5028 case CK_BitCast:
5029 case CK_LValueBitCast:
5030 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005031 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005032 e = cast->getSubExpr();
5033 continue;
5034
John McCallf85e1932011-06-15 23:02:42 +00005035 default:
5036 return false;
5037 }
5038 }
5039
5040 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5041 ObjCIvarDecl *ivar = ref->getDecl();
5042 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5043 return false;
5044
5045 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005046 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005047 return false;
5048
5049 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5050 owner.Indirect = true;
5051 return true;
5052 }
5053
5054 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5055 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5056 if (!var) return false;
5057 return considerVariable(var, ref, owner);
5058 }
5059
John McCallf85e1932011-06-15 23:02:42 +00005060 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5061 if (member->isArrow()) return false;
5062
5063 // Don't count this as an indirect ownership.
5064 e = member->getBase();
5065 continue;
5066 }
5067
John McCall4b9c2d22011-11-06 09:01:30 +00005068 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5069 // Only pay attention to pseudo-objects on property references.
5070 ObjCPropertyRefExpr *pre
5071 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5072 ->IgnoreParens());
5073 if (!pre) return false;
5074 if (pre->isImplicitProperty()) return false;
5075 ObjCPropertyDecl *property = pre->getExplicitProperty();
5076 if (!property->isRetaining() &&
5077 !(property->getPropertyIvarDecl() &&
5078 property->getPropertyIvarDecl()->getType()
5079 .getObjCLifetime() == Qualifiers::OCL_Strong))
5080 return false;
5081
5082 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005083 if (pre->isSuperReceiver()) {
5084 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5085 if (!owner.Variable)
5086 return false;
5087 owner.Loc = pre->getLocation();
5088 owner.Range = pre->getSourceRange();
5089 return true;
5090 }
John McCall4b9c2d22011-11-06 09:01:30 +00005091 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5092 ->getSourceExpr());
5093 continue;
5094 }
5095
John McCallf85e1932011-06-15 23:02:42 +00005096 // Array ivars?
5097
5098 return false;
5099 }
5100}
5101
5102namespace {
5103 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5104 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5105 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5106 Variable(variable), Capturer(0) {}
5107
5108 VarDecl *Variable;
5109 Expr *Capturer;
5110
5111 void VisitDeclRefExpr(DeclRefExpr *ref) {
5112 if (ref->getDecl() == Variable && !Capturer)
5113 Capturer = ref;
5114 }
5115
John McCallf85e1932011-06-15 23:02:42 +00005116 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5117 if (Capturer) return;
5118 Visit(ref->getBase());
5119 if (Capturer && ref->isFreeIvar())
5120 Capturer = ref;
5121 }
5122
5123 void VisitBlockExpr(BlockExpr *block) {
5124 // Look inside nested blocks
5125 if (block->getBlockDecl()->capturesVariable(Variable))
5126 Visit(block->getBlockDecl()->getBody());
5127 }
5128 };
5129}
5130
5131/// Check whether the given argument is a block which captures a
5132/// variable.
5133static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5134 assert(owner.Variable && owner.Loc.isValid());
5135
5136 e = e->IgnoreParenCasts();
5137 BlockExpr *block = dyn_cast<BlockExpr>(e);
5138 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5139 return 0;
5140
5141 FindCaptureVisitor visitor(S.Context, owner.Variable);
5142 visitor.Visit(block->getBlockDecl()->getBody());
5143 return visitor.Capturer;
5144}
5145
5146static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5147 RetainCycleOwner &owner) {
5148 assert(capturer);
5149 assert(owner.Variable && owner.Loc.isValid());
5150
5151 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5152 << owner.Variable << capturer->getSourceRange();
5153 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5154 << owner.Indirect << owner.Range;
5155}
5156
5157/// Check for a keyword selector that starts with the word 'add' or
5158/// 'set'.
5159static bool isSetterLikeSelector(Selector sel) {
5160 if (sel.isUnarySelector()) return false;
5161
Chris Lattner5f9e2722011-07-23 10:55:15 +00005162 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005163 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005164 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005165 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005166 else if (str.startswith("add")) {
5167 // Specially whitelist 'addOperationWithBlock:'.
5168 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5169 return false;
5170 str = str.substr(3);
5171 }
John McCallf85e1932011-06-15 23:02:42 +00005172 else
5173 return false;
5174
5175 if (str.empty()) return true;
5176 return !islower(str.front());
5177}
5178
5179/// Check a message send to see if it's likely to cause a retain cycle.
5180void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5181 // Only check instance methods whose selector looks like a setter.
5182 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5183 return;
5184
5185 // Try to find a variable that the receiver is strongly owned by.
5186 RetainCycleOwner owner;
5187 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005188 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005189 return;
5190 } else {
5191 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5192 owner.Variable = getCurMethodDecl()->getSelfDecl();
5193 owner.Loc = msg->getSuperLoc();
5194 owner.Range = msg->getSuperLoc();
5195 }
5196
5197 // Check whether the receiver is captured by any of the arguments.
5198 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5199 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5200 return diagnoseRetainCycle(*this, capturer, owner);
5201}
5202
5203/// Check a property assign to see if it's likely to cause a retain cycle.
5204void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5205 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005206 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005207 return;
5208
5209 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5210 diagnoseRetainCycle(*this, capturer, owner);
5211}
5212
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005213bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005214 QualType LHS, Expr *RHS) {
5215 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5216 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005217 return false;
5218 // strip off any implicit cast added to get to the one arc-specific
5219 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005220 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005221 Diag(Loc, diag::warn_arc_retained_assign)
5222 << (LT == Qualifiers::OCL_ExplicitNone)
5223 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005224 return true;
5225 }
5226 RHS = cast->getSubExpr();
5227 }
5228 return false;
John McCallf85e1932011-06-15 23:02:42 +00005229}
5230
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005231void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5232 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005233 QualType LHSType;
5234 // PropertyRef on LHS type need be directly obtained from
5235 // its declaration as it has a PsuedoType.
5236 ObjCPropertyRefExpr *PRE
5237 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5238 if (PRE && !PRE->isImplicitProperty()) {
5239 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5240 if (PD)
5241 LHSType = PD->getType();
5242 }
5243
5244 if (LHSType.isNull())
5245 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005246 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5247 return;
5248 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5249 // FIXME. Check for other life times.
5250 if (LT != Qualifiers::OCL_None)
5251 return;
5252
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005253 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005254 if (PRE->isImplicitProperty())
5255 return;
5256 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5257 if (!PD)
5258 return;
5259
5260 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005261 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5262 // when 'assign' attribute was not explicitly specified
5263 // by user, ignore it and rely on property type itself
5264 // for lifetime info.
5265 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5266 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5267 LHSType->isObjCRetainableType())
5268 return;
5269
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005270 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005271 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005272 Diag(Loc, diag::warn_arc_retained_property_assign)
5273 << RHS->getSourceRange();
5274 return;
5275 }
5276 RHS = cast->getSubExpr();
5277 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005278 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005279 }
5280}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005281
5282//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5283
5284namespace {
5285bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5286 SourceLocation StmtLoc,
5287 const NullStmt *Body) {
5288 // Do not warn if the body is a macro that expands to nothing, e.g:
5289 //
5290 // #define CALL(x)
5291 // if (condition)
5292 // CALL(0);
5293 //
5294 if (Body->hasLeadingEmptyMacro())
5295 return false;
5296
5297 // Get line numbers of statement and body.
5298 bool StmtLineInvalid;
5299 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5300 &StmtLineInvalid);
5301 if (StmtLineInvalid)
5302 return false;
5303
5304 bool BodyLineInvalid;
5305 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5306 &BodyLineInvalid);
5307 if (BodyLineInvalid)
5308 return false;
5309
5310 // Warn if null statement and body are on the same line.
5311 if (StmtLine != BodyLine)
5312 return false;
5313
5314 return true;
5315}
5316} // Unnamed namespace
5317
5318void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5319 const Stmt *Body,
5320 unsigned DiagID) {
5321 // Since this is a syntactic check, don't emit diagnostic for template
5322 // instantiations, this just adds noise.
5323 if (CurrentInstantiationScope)
5324 return;
5325
5326 // The body should be a null statement.
5327 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5328 if (!NBody)
5329 return;
5330
5331 // Do the usual checks.
5332 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5333 return;
5334
5335 Diag(NBody->getSemiLoc(), DiagID);
5336 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5337}
5338
5339void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5340 const Stmt *PossibleBody) {
5341 assert(!CurrentInstantiationScope); // Ensured by caller
5342
5343 SourceLocation StmtLoc;
5344 const Stmt *Body;
5345 unsigned DiagID;
5346 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5347 StmtLoc = FS->getRParenLoc();
5348 Body = FS->getBody();
5349 DiagID = diag::warn_empty_for_body;
5350 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5351 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5352 Body = WS->getBody();
5353 DiagID = diag::warn_empty_while_body;
5354 } else
5355 return; // Neither `for' nor `while'.
5356
5357 // The body should be a null statement.
5358 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5359 if (!NBody)
5360 return;
5361
5362 // Skip expensive checks if diagnostic is disabled.
5363 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5364 DiagnosticsEngine::Ignored)
5365 return;
5366
5367 // Do the usual checks.
5368 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5369 return;
5370
5371 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5372 // noise level low, emit diagnostics only if for/while is followed by a
5373 // CompoundStmt, e.g.:
5374 // for (int i = 0; i < n; i++);
5375 // {
5376 // a(i);
5377 // }
5378 // or if for/while is followed by a statement with more indentation
5379 // than for/while itself:
5380 // for (int i = 0; i < n; i++);
5381 // a(i);
5382 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5383 if (!ProbableTypo) {
5384 bool BodyColInvalid;
5385 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5386 PossibleBody->getLocStart(),
5387 &BodyColInvalid);
5388 if (BodyColInvalid)
5389 return;
5390
5391 bool StmtColInvalid;
5392 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5393 S->getLocStart(),
5394 &StmtColInvalid);
5395 if (StmtColInvalid)
5396 return;
5397
5398 if (BodyCol > StmtCol)
5399 ProbableTypo = true;
5400 }
5401
5402 if (ProbableTypo) {
5403 Diag(NBody->getSemiLoc(), DiagID);
5404 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5405 }
5406}