blob: 91f5ce581350f5da3bd825f14db1a88420b18c7a [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;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
302 return move(TheCallResult);
303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Nate Begeman0d15c532010-06-13 04:47:52 +0000358 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
376 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
440 };
441
442 // We can't check the value of a dependent argument.
443 if (TheCall->getArg(i)->isTypeDependent() ||
444 TheCall->getArg(i)->isValueDependent())
445 return false;
446
447 // Check that the immediate argument is actually a constant.
448 llvm::APSInt Result;
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this instruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > u)
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Richard Smith831421f2012-06-25 20:30:08 +0000461/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
462/// parameter with the FormatAttr's correct format_idx and firstDataArg.
463/// Returns true when the format fits the function and the FormatStringInfo has
464/// been populated.
465bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
466 FormatStringInfo *FSI) {
467 FSI->HasVAListArg = Format->getFirstArg() == 0;
468 FSI->FormatIdx = Format->getFormatIdx() - 1;
469 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000470
Richard Smith831421f2012-06-25 20:30:08 +0000471 // The way the format attribute works in GCC, the implicit this argument
472 // of member functions is counted. However, it doesn't appear in our own
473 // lists, so decrement format_idx in that case.
474 if (IsCXXMember) {
475 if(FSI->FormatIdx == 0)
476 return false;
477 --FSI->FormatIdx;
478 if (FSI->FirstDataArg != 0)
479 --FSI->FirstDataArg;
480 }
481 return true;
482}
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Richard Smith831421f2012-06-25 20:30:08 +0000484/// Handles the checks for format strings, non-POD arguments to vararg
485/// functions, and NULL arguments passed to non-NULL parameters.
486void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
487 unsigned NumArgs,
488 unsigned NumProtoArgs,
489 bool IsMemberFunction,
490 SourceLocation Loc,
491 SourceRange Range,
492 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000493 // FIXME: This mechanism should be abstracted to be less fragile and
494 // more efficient. For example, just map function ids to custom
495 // handlers.
496
Ted Kremenekc82faca2010-09-09 04:33:05 +0000497 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000498 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000499 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000500 I = FDecl->specific_attr_begin<FormatAttr>(),
501 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
502 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, Loc, Range))
503 HandledFormatString = true;
504
505 // Refuse POD arguments that weren't caught by the format string
506 // checks above.
507 if (!HandledFormatString && CallType != VariadicDoesNotApply)
508 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
509 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Ted Kremenekc82faca2010-09-09 04:33:05 +0000511 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000512 I = FDecl->specific_attr_begin<NonNullAttr>(),
513 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
514 CheckNonNullArguments(*I, Args, Loc);
515}
516
517/// CheckConstructorCall - Check a constructor call for correctness and safety
518/// properties not enforced by the C type system.
519void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
520 unsigned NumArgs,
521 const FunctionProtoType *Proto,
522 SourceLocation Loc) {
523 VariadicCallType CallType =
524 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
525 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
526 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
527}
528
529/// CheckFunctionCall - Check a direct function call for various correctness
530/// and safety properties not strictly enforced by the C type system.
531bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
532 const FunctionProtoType *Proto) {
533 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
534 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
535 TheCall->getCallee());
536 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
537 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
538 IsMemberFunction, TheCall->getRParenLoc(),
539 TheCall->getCallee()->getSourceRange(), CallType);
540
541 IdentifierInfo *FnInfo = FDecl->getIdentifier();
542 // None of the checks below are needed for functions that don't have
543 // simple names (e.g., C++ conversion functions).
544 if (!FnInfo)
545 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000546
Anna Zaks0a151a12012-01-17 00:37:07 +0000547 unsigned CMId = FDecl->getMemoryFunctionKind();
548 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000549 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000550
Anna Zaksd9b859a2012-01-13 21:52:01 +0000551 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000552 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000553 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000554 else if (CMId == Builtin::BIstrncat)
555 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000556 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000557 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000558
Anders Carlssond406bf02009-08-16 01:56:34 +0000559 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000560}
561
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000562bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
563 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000564 VariadicCallType CallType =
565 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000566
Richard Smith831421f2012-06-25 20:30:08 +0000567 checkCall(Method, Args, NumArgs, Method->param_size(),
568 /*IsMemberFunction=*/false,
569 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000570
571 return false;
572}
573
Richard Smith831421f2012-06-25 20:30:08 +0000574bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
575 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000576 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
577 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000578 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000580 QualType Ty = V->getType();
581 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000582 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Richard Smith831421f2012-06-25 20:30:08 +0000584 VariadicCallType CallType =
585 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
586 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000587
Richard Smith831421f2012-06-25 20:30:08 +0000588 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
589 NumProtoArgs, /*IsMemberFunction=*/false,
590 TheCall->getRParenLoc(),
591 TheCall->getCallee()->getSourceRange(), CallType);
592
Anders Carlssond406bf02009-08-16 01:56:34 +0000593 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000594}
595
Richard Smithff34d402012-04-12 05:08:17 +0000596ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
597 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000598 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
599 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000600
Richard Smithff34d402012-04-12 05:08:17 +0000601 // All these operations take one of the following forms:
602 enum {
603 // C __c11_atomic_init(A *, C)
604 Init,
605 // C __c11_atomic_load(A *, int)
606 Load,
607 // void __atomic_load(A *, CP, int)
608 Copy,
609 // C __c11_atomic_add(A *, M, int)
610 Arithmetic,
611 // C __atomic_exchange_n(A *, CP, int)
612 Xchg,
613 // void __atomic_exchange(A *, C *, CP, int)
614 GNUXchg,
615 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
616 C11CmpXchg,
617 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
618 GNUCmpXchg
619 } Form = Init;
620 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
621 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
622 // where:
623 // C is an appropriate type,
624 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
625 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
626 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
627 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000628
Richard Smithff34d402012-04-12 05:08:17 +0000629 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
630 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
631 && "need to update code for modified C11 atomics");
632 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
633 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
634 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
635 Op == AtomicExpr::AO__atomic_store_n ||
636 Op == AtomicExpr::AO__atomic_exchange_n ||
637 Op == AtomicExpr::AO__atomic_compare_exchange_n;
638 bool IsAddSub = false;
639
640 switch (Op) {
641 case AtomicExpr::AO__c11_atomic_init:
642 Form = Init;
643 break;
644
645 case AtomicExpr::AO__c11_atomic_load:
646 case AtomicExpr::AO__atomic_load_n:
647 Form = Load;
648 break;
649
650 case AtomicExpr::AO__c11_atomic_store:
651 case AtomicExpr::AO__atomic_load:
652 case AtomicExpr::AO__atomic_store:
653 case AtomicExpr::AO__atomic_store_n:
654 Form = Copy;
655 break;
656
657 case AtomicExpr::AO__c11_atomic_fetch_add:
658 case AtomicExpr::AO__c11_atomic_fetch_sub:
659 case AtomicExpr::AO__atomic_fetch_add:
660 case AtomicExpr::AO__atomic_fetch_sub:
661 case AtomicExpr::AO__atomic_add_fetch:
662 case AtomicExpr::AO__atomic_sub_fetch:
663 IsAddSub = true;
664 // Fall through.
665 case AtomicExpr::AO__c11_atomic_fetch_and:
666 case AtomicExpr::AO__c11_atomic_fetch_or:
667 case AtomicExpr::AO__c11_atomic_fetch_xor:
668 case AtomicExpr::AO__atomic_fetch_and:
669 case AtomicExpr::AO__atomic_fetch_or:
670 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000671 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000672 case AtomicExpr::AO__atomic_and_fetch:
673 case AtomicExpr::AO__atomic_or_fetch:
674 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000675 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000676 Form = Arithmetic;
677 break;
678
679 case AtomicExpr::AO__c11_atomic_exchange:
680 case AtomicExpr::AO__atomic_exchange_n:
681 Form = Xchg;
682 break;
683
684 case AtomicExpr::AO__atomic_exchange:
685 Form = GNUXchg;
686 break;
687
688 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
689 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
690 Form = C11CmpXchg;
691 break;
692
693 case AtomicExpr::AO__atomic_compare_exchange:
694 case AtomicExpr::AO__atomic_compare_exchange_n:
695 Form = GNUCmpXchg;
696 break;
697 }
698
699 // Check we have the right number of arguments.
700 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000701 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000702 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000703 << TheCall->getCallee()->getSourceRange();
704 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000705 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
706 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000707 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000708 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000709 << TheCall->getCallee()->getSourceRange();
710 return ExprError();
711 }
712
Richard Smithff34d402012-04-12 05:08:17 +0000713 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000714 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000715 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
716 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
717 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000718 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000719 << Ptr->getType() << Ptr->getSourceRange();
720 return ExprError();
721 }
722
Richard Smithff34d402012-04-12 05:08:17 +0000723 // For a __c11 builtin, this should be a pointer to an _Atomic type.
724 QualType AtomTy = pointerType->getPointeeType(); // 'A'
725 QualType ValType = AtomTy; // 'C'
726 if (IsC11) {
727 if (!AtomTy->isAtomicType()) {
728 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
729 << Ptr->getType() << Ptr->getSourceRange();
730 return ExprError();
731 }
732 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000733 }
Eli Friedman276b0612011-10-11 02:20:01 +0000734
Richard Smithff34d402012-04-12 05:08:17 +0000735 // For an arithmetic operation, the implied arithmetic must be well-formed.
736 if (Form == Arithmetic) {
737 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
738 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
739 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
740 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
741 return ExprError();
742 }
743 if (!IsAddSub && !ValType->isIntegerType()) {
744 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
745 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
746 return ExprError();
747 }
748 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
749 // For __atomic_*_n operations, the value type must be a scalar integral or
750 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000751 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000752 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
753 return ExprError();
754 }
755
756 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
757 // For GNU atomics, require a trivially-copyable type. This is not part of
758 // the GNU atomics specification, but we enforce it for sanity.
759 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000760 << Ptr->getType() << Ptr->getSourceRange();
761 return ExprError();
762 }
763
Richard Smithff34d402012-04-12 05:08:17 +0000764 // FIXME: For any builtin other than a load, the ValType must not be
765 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000766
767 switch (ValType.getObjCLifetime()) {
768 case Qualifiers::OCL_None:
769 case Qualifiers::OCL_ExplicitNone:
770 // okay
771 break;
772
773 case Qualifiers::OCL_Weak:
774 case Qualifiers::OCL_Strong:
775 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000776 // FIXME: Can this happen? By this point, ValType should be known
777 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000778 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
779 << ValType << Ptr->getSourceRange();
780 return ExprError();
781 }
782
783 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000784 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000785 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000786 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000787 ResultType = Context.BoolTy;
788
Richard Smithff34d402012-04-12 05:08:17 +0000789 // The type of a parameter passed 'by value'. In the GNU atomics, such
790 // arguments are actually passed as pointers.
791 QualType ByValType = ValType; // 'CP'
792 if (!IsC11 && !IsN)
793 ByValType = Ptr->getType();
794
Eli Friedman276b0612011-10-11 02:20:01 +0000795 // The first argument --- the pointer --- has a fixed type; we
796 // deduce the types of the rest of the arguments accordingly. Walk
797 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000798 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000799 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000800 if (i < NumVals[Form] + 1) {
801 switch (i) {
802 case 1:
803 // The second argument is the non-atomic operand. For arithmetic, this
804 // is always passed by value, and for a compare_exchange it is always
805 // passed by address. For the rest, GNU uses by-address and C11 uses
806 // by-value.
807 assert(Form != Load);
808 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
809 Ty = ValType;
810 else if (Form == Copy || Form == Xchg)
811 Ty = ByValType;
812 else if (Form == Arithmetic)
813 Ty = Context.getPointerDiffType();
814 else
815 Ty = Context.getPointerType(ValType.getUnqualifiedType());
816 break;
817 case 2:
818 // The third argument to compare_exchange / GNU exchange is a
819 // (pointer to a) desired value.
820 Ty = ByValType;
821 break;
822 case 3:
823 // The fourth argument to GNU compare_exchange is a 'weak' flag.
824 Ty = Context.BoolTy;
825 break;
826 }
Eli Friedman276b0612011-10-11 02:20:01 +0000827 } else {
828 // The order(s) are always converted to int.
829 Ty = Context.IntTy;
830 }
Richard Smithff34d402012-04-12 05:08:17 +0000831
Eli Friedman276b0612011-10-11 02:20:01 +0000832 InitializedEntity Entity =
833 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000834 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000835 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
836 if (Arg.isInvalid())
837 return true;
838 TheCall->setArg(i, Arg.get());
839 }
840
Richard Smithff34d402012-04-12 05:08:17 +0000841 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000842 SmallVector<Expr*, 5> SubExprs;
843 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000844 switch (Form) {
845 case Init:
846 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000847 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000848 break;
849 case Load:
850 SubExprs.push_back(TheCall->getArg(1)); // Order
851 break;
852 case Copy:
853 case Arithmetic:
854 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000855 SubExprs.push_back(TheCall->getArg(2)); // Order
856 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000857 break;
858 case GNUXchg:
859 // Note, AtomicExpr::getVal2() has a special case for this atomic.
860 SubExprs.push_back(TheCall->getArg(3)); // Order
861 SubExprs.push_back(TheCall->getArg(1)); // Val1
862 SubExprs.push_back(TheCall->getArg(2)); // Val2
863 break;
864 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000865 SubExprs.push_back(TheCall->getArg(3)); // Order
866 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000867 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000868 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000869 break;
870 case GNUCmpXchg:
871 SubExprs.push_back(TheCall->getArg(4)); // Order
872 SubExprs.push_back(TheCall->getArg(1)); // Val1
873 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
874 SubExprs.push_back(TheCall->getArg(2)); // Val2
875 SubExprs.push_back(TheCall->getArg(3)); // Weak
876 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000877 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000878
879 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
880 SubExprs.data(), SubExprs.size(),
881 ResultType, Op,
882 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000883}
884
885
John McCall5f8d6042011-08-27 01:09:30 +0000886/// checkBuiltinArgument - Given a call to a builtin function, perform
887/// normal type-checking on the given argument, updating the call in
888/// place. This is useful when a builtin function requires custom
889/// type-checking for some of its arguments but not necessarily all of
890/// them.
891///
892/// Returns true on error.
893static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
894 FunctionDecl *Fn = E->getDirectCallee();
895 assert(Fn && "builtin call without direct callee!");
896
897 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
898 InitializedEntity Entity =
899 InitializedEntity::InitializeParameter(S.Context, Param);
900
901 ExprResult Arg = E->getArg(0);
902 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
903 if (Arg.isInvalid())
904 return true;
905
906 E->setArg(ArgIndex, Arg.take());
907 return false;
908}
909
Chris Lattner5caa3702009-05-08 06:58:22 +0000910/// SemaBuiltinAtomicOverloaded - We have a call to a function like
911/// __sync_fetch_and_add, which is an overloaded function based on the pointer
912/// type of its first argument. The main ActOnCallExpr routines have already
913/// promoted the types of arguments because all of these calls are prototyped as
914/// void(...).
915///
916/// This function goes through and does final semantic checking for these
917/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000918ExprResult
919Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000920 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000921 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
922 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
923
924 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000925 if (TheCall->getNumArgs() < 1) {
926 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
927 << 0 << 1 << TheCall->getNumArgs()
928 << TheCall->getCallee()->getSourceRange();
929 return ExprError();
930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Chris Lattner5caa3702009-05-08 06:58:22 +0000932 // Inspect the first argument of the atomic builtin. This should always be
933 // a pointer type, whose element is an integral scalar or pointer type.
934 // Because it is a pointer type, we don't have to worry about any implicit
935 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000936 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000937 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000938 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
939 if (FirstArgResult.isInvalid())
940 return ExprError();
941 FirstArg = FirstArgResult.take();
942 TheCall->setArg(0, FirstArg);
943
John McCallf85e1932011-06-15 23:02:42 +0000944 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
945 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000946 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
947 << FirstArg->getType() << FirstArg->getSourceRange();
948 return ExprError();
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
John McCallf85e1932011-06-15 23:02:42 +0000951 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000952 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000953 !ValType->isBlockPointerType()) {
954 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
955 << FirstArg->getType() << FirstArg->getSourceRange();
956 return ExprError();
957 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000958
John McCallf85e1932011-06-15 23:02:42 +0000959 switch (ValType.getObjCLifetime()) {
960 case Qualifiers::OCL_None:
961 case Qualifiers::OCL_ExplicitNone:
962 // okay
963 break;
964
965 case Qualifiers::OCL_Weak:
966 case Qualifiers::OCL_Strong:
967 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000968 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000969 << ValType << FirstArg->getSourceRange();
970 return ExprError();
971 }
972
John McCallb45ae252011-10-05 07:41:44 +0000973 // Strip any qualifiers off ValType.
974 ValType = ValType.getUnqualifiedType();
975
Chandler Carruth8d13d222010-07-18 20:54:12 +0000976 // The majority of builtins return a value, but a few have special return
977 // types, so allow them to override appropriately below.
978 QualType ResultType = ValType;
979
Chris Lattner5caa3702009-05-08 06:58:22 +0000980 // We need to figure out which concrete builtin this maps onto. For example,
981 // __sync_fetch_and_add with a 2 byte object turns into
982 // __sync_fetch_and_add_2.
983#define BUILTIN_ROW(x) \
984 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
985 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner5caa3702009-05-08 06:58:22 +0000987 static const unsigned BuiltinIndices[][5] = {
988 BUILTIN_ROW(__sync_fetch_and_add),
989 BUILTIN_ROW(__sync_fetch_and_sub),
990 BUILTIN_ROW(__sync_fetch_and_or),
991 BUILTIN_ROW(__sync_fetch_and_and),
992 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner5caa3702009-05-08 06:58:22 +0000994 BUILTIN_ROW(__sync_add_and_fetch),
995 BUILTIN_ROW(__sync_sub_and_fetch),
996 BUILTIN_ROW(__sync_and_and_fetch),
997 BUILTIN_ROW(__sync_or_and_fetch),
998 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner5caa3702009-05-08 06:58:22 +00001000 BUILTIN_ROW(__sync_val_compare_and_swap),
1001 BUILTIN_ROW(__sync_bool_compare_and_swap),
1002 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001003 BUILTIN_ROW(__sync_lock_release),
1004 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001005 };
Mike Stump1eb44332009-09-09 15:08:12 +00001006#undef BUILTIN_ROW
1007
Chris Lattner5caa3702009-05-08 06:58:22 +00001008 // Determine the index of the size.
1009 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001010 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001011 case 1: SizeIndex = 0; break;
1012 case 2: SizeIndex = 1; break;
1013 case 4: SizeIndex = 2; break;
1014 case 8: SizeIndex = 3; break;
1015 case 16: SizeIndex = 4; break;
1016 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001017 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1018 << FirstArg->getType() << FirstArg->getSourceRange();
1019 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 }
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner5caa3702009-05-08 06:58:22 +00001022 // Each of these builtins has one pointer argument, followed by some number of
1023 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1024 // that we ignore. Find out which row of BuiltinIndices to read from as well
1025 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001026 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 unsigned BuiltinIndex, NumFixed = 1;
1028 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001029 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001030 case Builtin::BI__sync_fetch_and_add:
1031 case Builtin::BI__sync_fetch_and_add_1:
1032 case Builtin::BI__sync_fetch_and_add_2:
1033 case Builtin::BI__sync_fetch_and_add_4:
1034 case Builtin::BI__sync_fetch_and_add_8:
1035 case Builtin::BI__sync_fetch_and_add_16:
1036 BuiltinIndex = 0;
1037 break;
1038
1039 case Builtin::BI__sync_fetch_and_sub:
1040 case Builtin::BI__sync_fetch_and_sub_1:
1041 case Builtin::BI__sync_fetch_and_sub_2:
1042 case Builtin::BI__sync_fetch_and_sub_4:
1043 case Builtin::BI__sync_fetch_and_sub_8:
1044 case Builtin::BI__sync_fetch_and_sub_16:
1045 BuiltinIndex = 1;
1046 break;
1047
1048 case Builtin::BI__sync_fetch_and_or:
1049 case Builtin::BI__sync_fetch_and_or_1:
1050 case Builtin::BI__sync_fetch_and_or_2:
1051 case Builtin::BI__sync_fetch_and_or_4:
1052 case Builtin::BI__sync_fetch_and_or_8:
1053 case Builtin::BI__sync_fetch_and_or_16:
1054 BuiltinIndex = 2;
1055 break;
1056
1057 case Builtin::BI__sync_fetch_and_and:
1058 case Builtin::BI__sync_fetch_and_and_1:
1059 case Builtin::BI__sync_fetch_and_and_2:
1060 case Builtin::BI__sync_fetch_and_and_4:
1061 case Builtin::BI__sync_fetch_and_and_8:
1062 case Builtin::BI__sync_fetch_and_and_16:
1063 BuiltinIndex = 3;
1064 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregora9766412011-11-28 16:30:08 +00001066 case Builtin::BI__sync_fetch_and_xor:
1067 case Builtin::BI__sync_fetch_and_xor_1:
1068 case Builtin::BI__sync_fetch_and_xor_2:
1069 case Builtin::BI__sync_fetch_and_xor_4:
1070 case Builtin::BI__sync_fetch_and_xor_8:
1071 case Builtin::BI__sync_fetch_and_xor_16:
1072 BuiltinIndex = 4;
1073 break;
1074
1075 case Builtin::BI__sync_add_and_fetch:
1076 case Builtin::BI__sync_add_and_fetch_1:
1077 case Builtin::BI__sync_add_and_fetch_2:
1078 case Builtin::BI__sync_add_and_fetch_4:
1079 case Builtin::BI__sync_add_and_fetch_8:
1080 case Builtin::BI__sync_add_and_fetch_16:
1081 BuiltinIndex = 5;
1082 break;
1083
1084 case Builtin::BI__sync_sub_and_fetch:
1085 case Builtin::BI__sync_sub_and_fetch_1:
1086 case Builtin::BI__sync_sub_and_fetch_2:
1087 case Builtin::BI__sync_sub_and_fetch_4:
1088 case Builtin::BI__sync_sub_and_fetch_8:
1089 case Builtin::BI__sync_sub_and_fetch_16:
1090 BuiltinIndex = 6;
1091 break;
1092
1093 case Builtin::BI__sync_and_and_fetch:
1094 case Builtin::BI__sync_and_and_fetch_1:
1095 case Builtin::BI__sync_and_and_fetch_2:
1096 case Builtin::BI__sync_and_and_fetch_4:
1097 case Builtin::BI__sync_and_and_fetch_8:
1098 case Builtin::BI__sync_and_and_fetch_16:
1099 BuiltinIndex = 7;
1100 break;
1101
1102 case Builtin::BI__sync_or_and_fetch:
1103 case Builtin::BI__sync_or_and_fetch_1:
1104 case Builtin::BI__sync_or_and_fetch_2:
1105 case Builtin::BI__sync_or_and_fetch_4:
1106 case Builtin::BI__sync_or_and_fetch_8:
1107 case Builtin::BI__sync_or_and_fetch_16:
1108 BuiltinIndex = 8;
1109 break;
1110
1111 case Builtin::BI__sync_xor_and_fetch:
1112 case Builtin::BI__sync_xor_and_fetch_1:
1113 case Builtin::BI__sync_xor_and_fetch_2:
1114 case Builtin::BI__sync_xor_and_fetch_4:
1115 case Builtin::BI__sync_xor_and_fetch_8:
1116 case Builtin::BI__sync_xor_and_fetch_16:
1117 BuiltinIndex = 9;
1118 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Chris Lattner5caa3702009-05-08 06:58:22 +00001120 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001121 case Builtin::BI__sync_val_compare_and_swap_1:
1122 case Builtin::BI__sync_val_compare_and_swap_2:
1123 case Builtin::BI__sync_val_compare_and_swap_4:
1124 case Builtin::BI__sync_val_compare_and_swap_8:
1125 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001126 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001127 NumFixed = 2;
1128 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001129
Chris Lattner5caa3702009-05-08 06:58:22 +00001130 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001131 case Builtin::BI__sync_bool_compare_and_swap_1:
1132 case Builtin::BI__sync_bool_compare_and_swap_2:
1133 case Builtin::BI__sync_bool_compare_and_swap_4:
1134 case Builtin::BI__sync_bool_compare_and_swap_8:
1135 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001136 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001137 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001138 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001139 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001140
1141 case Builtin::BI__sync_lock_test_and_set:
1142 case Builtin::BI__sync_lock_test_and_set_1:
1143 case Builtin::BI__sync_lock_test_and_set_2:
1144 case Builtin::BI__sync_lock_test_and_set_4:
1145 case Builtin::BI__sync_lock_test_and_set_8:
1146 case Builtin::BI__sync_lock_test_and_set_16:
1147 BuiltinIndex = 12;
1148 break;
1149
Chris Lattner5caa3702009-05-08 06:58:22 +00001150 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001151 case Builtin::BI__sync_lock_release_1:
1152 case Builtin::BI__sync_lock_release_2:
1153 case Builtin::BI__sync_lock_release_4:
1154 case Builtin::BI__sync_lock_release_8:
1155 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001156 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001157 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001158 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001159 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001160
1161 case Builtin::BI__sync_swap:
1162 case Builtin::BI__sync_swap_1:
1163 case Builtin::BI__sync_swap_2:
1164 case Builtin::BI__sync_swap_4:
1165 case Builtin::BI__sync_swap_8:
1166 case Builtin::BI__sync_swap_16:
1167 BuiltinIndex = 14;
1168 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001169 }
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattner5caa3702009-05-08 06:58:22 +00001171 // Now that we know how many fixed arguments we expect, first check that we
1172 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001173 if (TheCall->getNumArgs() < 1+NumFixed) {
1174 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1175 << 0 << 1+NumFixed << TheCall->getNumArgs()
1176 << TheCall->getCallee()->getSourceRange();
1177 return ExprError();
1178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001180 // Get the decl for the concrete builtin from this, we can tell what the
1181 // concrete integer type we should convert to is.
1182 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1183 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1184 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001185 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001186 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1187 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001188
John McCallf871d0c2010-08-07 06:22:56 +00001189 // The first argument --- the pointer --- has a fixed type; we
1190 // deduce the types of the rest of the arguments accordingly. Walk
1191 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001192 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001193 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Chris Lattner5caa3702009-05-08 06:58:22 +00001195 // GCC does an implicit conversion to the pointer or integer ValType. This
1196 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001197 // Initialize the argument.
1198 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1199 ValType, /*consume*/ false);
1200 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001201 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001202 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Chris Lattner5caa3702009-05-08 06:58:22 +00001204 // Okay, we have something that *can* be converted to the right type. Check
1205 // to see if there is a potentially weird extension going on here. This can
1206 // happen when you do an atomic operation on something like an char* and
1207 // pass in 42. The 42 gets converted to char. This is even more strange
1208 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001209 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001210 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001213 ASTContext& Context = this->getASTContext();
1214
1215 // Create a new DeclRefExpr to refer to the new decl.
1216 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1217 Context,
1218 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001219 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001220 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001221 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001222 DRE->getLocation(),
1223 NewBuiltinDecl->getType(),
1224 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattner5caa3702009-05-08 06:58:22 +00001226 // Set the callee in the CallExpr.
1227 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001228 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001229 if (PromotedCall.isInvalid())
1230 return ExprError();
1231 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001233 // Change the result type of the call to match the original value type. This
1234 // is arbitrary, but the codegen for these builtins ins design to handle it
1235 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001236 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001237
1238 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001239}
1240
Chris Lattner69039812009-02-18 06:01:06 +00001241/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001242/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001243/// Note: It might also make sense to do the UTF-16 conversion here (would
1244/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001245bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001246 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001247 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1248
Douglas Gregor5cee1192011-07-27 05:40:30 +00001249 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001250 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1251 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001252 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001253 }
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001255 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001256 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001257 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001258 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001259 const UTF8 *FromPtr = (UTF8 *)String.data();
1260 UTF16 *ToPtr = &ToBuf[0];
1261
1262 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1263 &ToPtr, ToPtr + NumBytes,
1264 strictConversion);
1265 // Check for conversion failure.
1266 if (Result != conversionOK)
1267 Diag(Arg->getLocStart(),
1268 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1269 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001270 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001271}
1272
Chris Lattnerc27c6652007-12-20 00:05:45 +00001273/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1274/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001275bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1276 Expr *Fn = TheCall->getCallee();
1277 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001278 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001279 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001280 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1281 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001282 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001283 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001284 return true;
1285 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001286
1287 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001288 return Diag(TheCall->getLocEnd(),
1289 diag::err_typecheck_call_too_few_args_at_least)
1290 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001291 }
1292
John McCall5f8d6042011-08-27 01:09:30 +00001293 // Type-check the first argument normally.
1294 if (checkBuiltinArgument(*this, TheCall, 0))
1295 return true;
1296
Chris Lattnerc27c6652007-12-20 00:05:45 +00001297 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001298 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001299 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001300 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001301 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001302 else if (FunctionDecl *FD = getCurFunctionDecl())
1303 isVariadic = FD->isVariadic();
1304 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001305 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Chris Lattnerc27c6652007-12-20 00:05:45 +00001307 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001308 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1309 return true;
1310 }
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Chris Lattner30ce3442007-12-19 23:59:04 +00001312 // Verify that the second argument to the builtin is the last argument of the
1313 // current function or method.
1314 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001315 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Anders Carlsson88cf2262008-02-11 04:20:54 +00001317 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1318 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001319 // FIXME: This isn't correct for methods (results in bogus warning).
1320 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001321 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001322 if (CurBlock)
1323 LastArg = *(CurBlock->TheDecl->param_end()-1);
1324 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001325 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001326 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001327 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001328 SecondArgIsLastNamedArgument = PV == LastArg;
1329 }
1330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Chris Lattner30ce3442007-12-19 23:59:04 +00001332 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001333 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001334 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1335 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001336}
Chris Lattner30ce3442007-12-19 23:59:04 +00001337
Chris Lattner1b9a0792007-12-20 00:26:33 +00001338/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1339/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001340bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1341 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001342 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001343 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001344 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001345 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001346 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001347 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001348 << SourceRange(TheCall->getArg(2)->getLocStart(),
1349 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001350
John Wiegley429bb272011-04-08 18:41:53 +00001351 ExprResult OrigArg0 = TheCall->getArg(0);
1352 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001353
Chris Lattner1b9a0792007-12-20 00:26:33 +00001354 // Do standard promotions between the two arguments, returning their common
1355 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001356 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001357 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1358 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001359
1360 // Make sure any conversions are pushed back into the call; this is
1361 // type safe since unordered compare builtins are declared as "_Bool
1362 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001363 TheCall->setArg(0, OrigArg0.get());
1364 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001365
John Wiegley429bb272011-04-08 18:41:53 +00001366 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001367 return false;
1368
Chris Lattner1b9a0792007-12-20 00:26:33 +00001369 // If the common type isn't a real floating type, then the arguments were
1370 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001371 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001372 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001373 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001374 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1375 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner1b9a0792007-12-20 00:26:33 +00001377 return false;
1378}
1379
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001380/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1381/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001382/// to check everything. We expect the last argument to be a floating point
1383/// value.
1384bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1385 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001386 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001387 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001388 if (TheCall->getNumArgs() > NumArgs)
1389 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001390 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001391 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001392 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001393 (*(TheCall->arg_end()-1))->getLocEnd());
1394
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001395 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Eli Friedman9ac6f622009-08-31 20:06:00 +00001397 if (OrigArg->isTypeDependent())
1398 return false;
1399
Chris Lattner81368fb2010-05-06 05:50:07 +00001400 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001401 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001402 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001403 diag::err_typecheck_call_invalid_unary_fp)
1404 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Chris Lattner81368fb2010-05-06 05:50:07 +00001406 // If this is an implicit conversion from float -> double, remove it.
1407 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1408 Expr *CastArg = Cast->getSubExpr();
1409 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1410 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1411 "promotion from float to double is the only expected cast here");
1412 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001413 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001414 }
1415 }
1416
Eli Friedman9ac6f622009-08-31 20:06:00 +00001417 return false;
1418}
1419
Eli Friedmand38617c2008-05-14 19:38:39 +00001420/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1421// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001422ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001423 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001424 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001425 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001426 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001427 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001428
Nate Begeman37b6a572010-06-08 00:16:34 +00001429 // Determine which of the following types of shufflevector we're checking:
1430 // 1) unary, vector mask: (lhs, mask)
1431 // 2) binary, vector mask: (lhs, rhs, mask)
1432 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1433 QualType resType = TheCall->getArg(0)->getType();
1434 unsigned numElements = 0;
1435
Douglas Gregorcde01732009-05-19 22:10:17 +00001436 if (!TheCall->getArg(0)->isTypeDependent() &&
1437 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001438 QualType LHSType = TheCall->getArg(0)->getType();
1439 QualType RHSType = TheCall->getArg(1)->getType();
1440
1441 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001442 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001443 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001444 TheCall->getArg(1)->getLocEnd());
1445 return ExprError();
1446 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001447
1448 numElements = LHSType->getAs<VectorType>()->getNumElements();
1449 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Nate Begeman37b6a572010-06-08 00:16:34 +00001451 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1452 // with mask. If so, verify that RHS is an integer vector type with the
1453 // same number of elts as lhs.
1454 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001455 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001456 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1457 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1458 << SourceRange(TheCall->getArg(1)->getLocStart(),
1459 TheCall->getArg(1)->getLocEnd());
1460 numResElements = numElements;
1461 }
1462 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001463 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001464 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001465 TheCall->getArg(1)->getLocEnd());
1466 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001467 } else if (numElements != numResElements) {
1468 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001469 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001470 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001471 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001472 }
1473
1474 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001475 if (TheCall->getArg(i)->isTypeDependent() ||
1476 TheCall->getArg(i)->isValueDependent())
1477 continue;
1478
Nate Begeman37b6a572010-06-08 00:16:34 +00001479 llvm::APSInt Result(32);
1480 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1481 return ExprError(Diag(TheCall->getLocStart(),
1482 diag::err_shufflevector_nonconstant_argument)
1483 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001484
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001485 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001486 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001487 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001488 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001489 }
1490
Chris Lattner5f9e2722011-07-23 10:55:15 +00001491 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001492
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001493 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001494 exprs.push_back(TheCall->getArg(i));
1495 TheCall->setArg(i, 0);
1496 }
1497
Nate Begemana88dc302009-08-12 02:10:25 +00001498 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001499 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001500 TheCall->getCallee()->getLocStart(),
1501 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001502}
Chris Lattner30ce3442007-12-19 23:59:04 +00001503
Daniel Dunbar4493f792008-07-21 22:59:13 +00001504/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1505// This is declared to take (const void*, ...) and can take two
1506// optional constant int args.
1507bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001508 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001509
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001510 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001511 return Diag(TheCall->getLocEnd(),
1512 diag::err_typecheck_call_too_many_args_at_most)
1513 << 0 /*function call*/ << 3 << NumArgs
1514 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001515
1516 // Argument 0 is checked for us and the remaining arguments must be
1517 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001518 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001519 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001520
1521 // We can't check the value of a dependent argument.
1522 if (Arg->isTypeDependent() || Arg->isValueDependent())
1523 continue;
1524
Eli Friedman9aef7262009-12-04 00:30:06 +00001525 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001526 if (SemaBuiltinConstantArg(TheCall, i, Result))
1527 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Daniel Dunbar4493f792008-07-21 22:59:13 +00001529 // FIXME: gcc issues a warning and rewrites these to 0. These
1530 // seems especially odd for the third argument since the default
1531 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001532 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001533 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001534 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001535 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001536 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001537 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001538 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001539 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001540 }
1541 }
1542
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001543 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001544}
1545
Eric Christopher691ebc32010-04-17 02:26:23 +00001546/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1547/// TheCall is a constant expression.
1548bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1549 llvm::APSInt &Result) {
1550 Expr *Arg = TheCall->getArg(ArgNum);
1551 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1552 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1553
1554 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1555
1556 if (!Arg->isIntegerConstantExpr(Result, Context))
1557 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001558 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001559
Chris Lattner21fb98e2009-09-23 06:06:36 +00001560 return false;
1561}
1562
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001563/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1564/// int type). This simply type checks that type is one of the defined
1565/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001566// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001567bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001568 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001569
1570 // We can't check the value of a dependent argument.
1571 if (TheCall->getArg(1)->isTypeDependent() ||
1572 TheCall->getArg(1)->isValueDependent())
1573 return false;
1574
Eric Christopher691ebc32010-04-17 02:26:23 +00001575 // Check constant-ness first.
1576 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1577 return true;
1578
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001579 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001580 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001581 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1582 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001583 }
1584
1585 return false;
1586}
1587
Eli Friedman586d6a82009-05-03 06:04:26 +00001588/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001589/// This checks that val is a constant 1.
1590bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1591 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001592 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001593
Eric Christopher691ebc32010-04-17 02:26:23 +00001594 // TODO: This is less than ideal. Overload this to take a value.
1595 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1596 return true;
1597
1598 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001599 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1600 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1601
1602 return false;
1603}
1604
Richard Smith831421f2012-06-25 20:30:08 +00001605// Determine if an expression is a string literal or constant string.
1606// If this function returns false on the arguments to a function expecting a
1607// format string, we will usually need to emit a warning.
1608// True string literals are then checked by CheckFormatString.
1609Sema::StringLiteralCheckType
1610Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1611 unsigned NumArgs, bool HasVAListArg,
1612 unsigned format_idx, unsigned firstDataArg,
1613 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001614 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001615 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001616 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001617
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001618 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001619
David Blaikiea73cdcb2012-02-10 21:07:25 +00001620 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1621 // Technically -Wformat-nonliteral does not warn about this case.
1622 // The behavior of printf and friends in this case is implementation
1623 // dependent. Ideally if the format string cannot be null then
1624 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001625 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001626
Ted Kremenekd30ef872009-01-12 23:09:09 +00001627 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001628 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001629 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001630 // The expression is a literal if both sub-expressions were, and it was
1631 // completely checked only if both sub-expressions were checked.
1632 const AbstractConditionalOperator *C =
1633 cast<AbstractConditionalOperator>(E);
1634 StringLiteralCheckType Left =
1635 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1636 HasVAListArg, format_idx, firstDataArg,
1637 Type, inFunctionCall);
1638 if (Left == SLCT_NotALiteral)
1639 return SLCT_NotALiteral;
1640 StringLiteralCheckType Right =
1641 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1642 HasVAListArg, format_idx, firstDataArg,
1643 Type, inFunctionCall);
1644 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001645 }
1646
1647 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001648 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1649 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001650 }
1651
John McCall56ca35d2011-02-17 10:25:35 +00001652 case Stmt::OpaqueValueExprClass:
1653 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1654 E = src;
1655 goto tryAgain;
1656 }
Richard Smith831421f2012-06-25 20:30:08 +00001657 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001658
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001659 case Stmt::PredefinedExprClass:
1660 // While __func__, etc., are technically not string literals, they
1661 // cannot contain format specifiers and thus are not a security
1662 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001663 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001664
Ted Kremenek082d9362009-03-20 21:35:28 +00001665 case Stmt::DeclRefExprClass: {
1666 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Ted Kremenek082d9362009-03-20 21:35:28 +00001668 // As an exception, do not flag errors for variables binding to
1669 // const string literals.
1670 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1671 bool isConstant = false;
1672 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001673
Ted Kremenek082d9362009-03-20 21:35:28 +00001674 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1675 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001676 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001677 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001678 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001679 } else if (T->isObjCObjectPointerType()) {
1680 // In ObjC, there is usually no "const ObjectPointer" type,
1681 // so don't check if the pointee type is constant.
1682 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Ted Kremenek082d9362009-03-20 21:35:28 +00001685 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001686 if (const Expr *Init = VD->getAnyInitializer()) {
1687 // Look through initializers like const char c[] = { "foo" }
1688 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1689 if (InitList->isStringLiteralInit())
1690 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1691 }
Richard Smith831421f2012-06-25 20:30:08 +00001692 return checkFormatStringExpr(Init, Args, NumArgs,
1693 HasVAListArg, format_idx,
1694 firstDataArg, Type,
1695 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001696 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Anders Carlssond966a552009-06-28 19:55:58 +00001699 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1700 // special check to see if the format string is a function parameter
1701 // of the function calling the printf function. If the function
1702 // has an attribute indicating it is a printf-like function, then we
1703 // should suppress warnings concerning non-literals being used in a call
1704 // to a vprintf function. For example:
1705 //
1706 // void
1707 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1708 // va_list ap;
1709 // va_start(ap, fmt);
1710 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1711 // ...
1712 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001713 if (HasVAListArg) {
1714 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1715 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1716 int PVIndex = PV->getFunctionScopeIndex() + 1;
1717 for (specific_attr_iterator<FormatAttr>
1718 i = ND->specific_attr_begin<FormatAttr>(),
1719 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1720 FormatAttr *PVFormat = *i;
1721 // adjust for implicit parameter
1722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1723 if (MD->isInstance())
1724 ++PVIndex;
1725 // We also check if the formats are compatible.
1726 // We can't pass a 'scanf' string to a 'printf' function.
1727 if (PVIndex == PVFormat->getFormatIdx() &&
1728 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001729 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001730 }
1731 }
1732 }
1733 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Richard Smith831421f2012-06-25 20:30:08 +00001736 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001738
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001739 case Stmt::CallExprClass:
1740 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001741 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001742 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1743 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1744 unsigned ArgIndex = FA->getFormatIdx();
1745 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1746 if (MD->isInstance())
1747 --ArgIndex;
1748 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Richard Smith831421f2012-06-25 20:30:08 +00001750 return checkFormatStringExpr(Arg, Args, NumArgs,
1751 HasVAListArg, format_idx, firstDataArg,
1752 Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001753 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1754 unsigned BuiltinID = FD->getBuiltinID();
1755 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1756 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1757 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001758 return checkFormatStringExpr(Arg, Args, NumArgs,
1759 HasVAListArg, format_idx,
1760 firstDataArg, Type, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001761 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001762 }
1763 }
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Richard Smith831421f2012-06-25 20:30:08 +00001765 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001766 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001767 case Stmt::ObjCStringLiteralClass:
1768 case Stmt::StringLiteralClass: {
1769 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Ted Kremenek082d9362009-03-20 21:35:28 +00001771 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001772 StrE = ObjCFExpr->getString();
1773 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001774 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Ted Kremenekd30ef872009-01-12 23:09:09 +00001776 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001777 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001778 firstDataArg, Type, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001779 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Richard Smith831421f2012-06-25 20:30:08 +00001782 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001783 }
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Ted Kremenek082d9362009-03-20 21:35:28 +00001785 default:
Richard Smith831421f2012-06-25 20:30:08 +00001786 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001787 }
1788}
1789
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001790void
Mike Stump1eb44332009-09-09 15:08:12 +00001791Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001792 const Expr * const *ExprArgs,
1793 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001794 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1795 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001796 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001797 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001798 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001799 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001800 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001801 }
1802}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001803
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001804Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1805 return llvm::StringSwitch<FormatStringType>(Format->getType())
1806 .Case("scanf", FST_Scanf)
1807 .Cases("printf", "printf0", FST_Printf)
1808 .Cases("NSString", "CFString", FST_NSString)
1809 .Case("strftime", FST_Strftime)
1810 .Case("strfmon", FST_Strfmon)
1811 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1812 .Default(FST_Unknown);
1813}
1814
Ted Kremenek826a3452010-07-16 02:11:22 +00001815/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1816/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001817/// Returns true if a format string has been fully checked.
1818bool Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1819 bool IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
1820 return CheckFormatArguments(Format, TheCall->getArgs(),
1821 TheCall->getNumArgs(),
1822 IsCXXMember, TheCall->getRParenLoc(),
1823 TheCall->getCallee()->getSourceRange());
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001824}
1825
Richard Smith831421f2012-06-25 20:30:08 +00001826bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001827 unsigned NumArgs, bool IsCXXMember,
1828 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001829 FormatStringInfo FSI;
1830 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1831 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1832 FSI.FirstDataArg, GetFormatStringType(Format),
1833 Loc, Range);
1834 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001835}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001836
Richard Smith831421f2012-06-25 20:30:08 +00001837bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001838 bool HasVAListArg, unsigned format_idx,
1839 unsigned firstDataArg, FormatStringType Type,
1840 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001841 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001842 if (format_idx >= NumArgs) {
1843 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001844 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001847 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Chris Lattner59907c42007-08-10 20:18:51 +00001849 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001850 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001851 // Dynamically generated format strings are difficult to
1852 // automatically vet at compile time. Requiring that format strings
1853 // are string literals: (1) permits the checking of format strings by
1854 // the compiler and thereby (2) can practically remove the source of
1855 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001856
Mike Stump1eb44332009-09-09 15:08:12 +00001857 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001858 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001860 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001861 StringLiteralCheckType CT =
1862 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1863 format_idx, firstDataArg, Type);
1864 if (CT != SLCT_NotALiteral)
1865 // Literal format string found, check done!
1866 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001867
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001868 // Strftime is particular as it always uses a single 'time' argument,
1869 // so it is safe to pass a non-literal string.
1870 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001871 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001872
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001873 // Do not emit diag when the string param is a macro expansion and the
1874 // format is either NSString or CFString. This is a hack to prevent
1875 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1876 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001877 if (Type == FST_NSString &&
1878 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001879 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001880
Chris Lattner655f1412009-04-29 04:59:47 +00001881 // If there are no arguments specified, warn with -Wformat-security, otherwise
1882 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001883 if (NumArgs == format_idx+1)
1884 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001885 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001886 << OrigFormatExpr->getSourceRange();
1887 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001888 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001889 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001890 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001891 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001892}
Ted Kremenek71895b92007-08-14 17:39:48 +00001893
Ted Kremeneke0e53132010-01-28 23:39:18 +00001894namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001895class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1896protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001897 Sema &S;
1898 const StringLiteral *FExpr;
1899 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001900 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001901 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001902 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001903 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001904 const Expr * const *Args;
1905 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001906 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001907 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001908 bool usesPositionalArgs;
1909 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001910 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001911public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001912 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001913 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001914 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001915 Expr **args, unsigned numArgs,
1916 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001917 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001918 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1919 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001920 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001921 usesPositionalArgs(false), atFirstArg(true),
1922 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001923 CoveredArgs.resize(numDataArgs);
1924 CoveredArgs.reset();
1925 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001926
Ted Kremenek07d161f2010-01-29 01:50:07 +00001927 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001928
Ted Kremenek826a3452010-07-16 02:11:22 +00001929 void HandleIncompleteSpecifier(const char *startSpecifier,
1930 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001931
1932 void HandleNonStandardLengthModifier(
1933 const analyze_format_string::LengthModifier &LM,
1934 const char *startSpecifier, unsigned specifierLen);
1935
1936 void HandleNonStandardConversionSpecifier(
1937 const analyze_format_string::ConversionSpecifier &CS,
1938 const char *startSpecifier, unsigned specifierLen);
1939
1940 void HandleNonStandardConversionSpecification(
1941 const analyze_format_string::LengthModifier &LM,
1942 const analyze_format_string::ConversionSpecifier &CS,
1943 const char *startSpecifier, unsigned specifierLen);
1944
Hans Wennborgf8562642012-03-09 10:10:54 +00001945 virtual void HandlePosition(const char *startPos, unsigned posLen);
1946
Ted Kremenekefaff192010-02-27 01:41:03 +00001947 virtual void HandleInvalidPosition(const char *startSpecifier,
1948 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001949 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001950
1951 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1952
Ted Kremeneke0e53132010-01-28 23:39:18 +00001953 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001954
Richard Trieu55733de2011-10-28 00:41:25 +00001955 template <typename Range>
1956 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1957 const Expr *ArgumentExpr,
1958 PartialDiagnostic PDiag,
1959 SourceLocation StringLoc,
1960 bool IsStringLocation, Range StringRange,
1961 FixItHint Fixit = FixItHint());
1962
Ted Kremenek826a3452010-07-16 02:11:22 +00001963protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001964 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1965 const char *startSpec,
1966 unsigned specifierLen,
1967 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001968
1969 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1970 const char *startSpec,
1971 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001972
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001973 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001974 CharSourceRange getSpecifierRange(const char *startSpecifier,
1975 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001976 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977
Ted Kremenek0d277352010-01-29 01:06:55 +00001978 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001979
1980 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1981 const analyze_format_string::ConversionSpecifier &CS,
1982 const char *startSpecifier, unsigned specifierLen,
1983 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001984
1985 template <typename Range>
1986 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1987 bool IsStringLocation, Range StringRange,
1988 FixItHint Fixit = FixItHint());
1989
1990 void CheckPositionalAndNonpositionalArgs(
1991 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001992};
1993}
1994
Ted Kremenek826a3452010-07-16 02:11:22 +00001995SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001996 return OrigFormatExpr->getSourceRange();
1997}
1998
Ted Kremenek826a3452010-07-16 02:11:22 +00001999CharSourceRange CheckFormatHandler::
2000getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002001 SourceLocation Start = getLocationOfByte(startSpecifier);
2002 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2003
2004 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002005 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002006
2007 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002008}
2009
Ted Kremenek826a3452010-07-16 02:11:22 +00002010SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002011 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002012}
2013
Ted Kremenek826a3452010-07-16 02:11:22 +00002014void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2015 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002016 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2017 getLocationOfByte(startSpecifier),
2018 /*IsStringLocation*/true,
2019 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002020}
2021
Hans Wennborg76517422012-02-22 10:17:01 +00002022void CheckFormatHandler::HandleNonStandardLengthModifier(
2023 const analyze_format_string::LengthModifier &LM,
2024 const char *startSpecifier, unsigned specifierLen) {
2025 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002026 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00002027 getLocationOfByte(LM.getStart()),
2028 /*IsStringLocation*/true,
2029 getSpecifierRange(startSpecifier, specifierLen));
2030}
2031
2032void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2033 const analyze_format_string::ConversionSpecifier &CS,
2034 const char *startSpecifier, unsigned specifierLen) {
2035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002036 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00002037 getLocationOfByte(CS.getStart()),
2038 /*IsStringLocation*/true,
2039 getSpecifierRange(startSpecifier, specifierLen));
2040}
2041
2042void CheckFormatHandler::HandleNonStandardConversionSpecification(
2043 const analyze_format_string::LengthModifier &LM,
2044 const analyze_format_string::ConversionSpecifier &CS,
2045 const char *startSpecifier, unsigned specifierLen) {
2046 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
2047 << LM.toString() << CS.toString(),
2048 getLocationOfByte(LM.getStart()),
2049 /*IsStringLocation*/true,
2050 getSpecifierRange(startSpecifier, specifierLen));
2051}
2052
Hans Wennborgf8562642012-03-09 10:10:54 +00002053void CheckFormatHandler::HandlePosition(const char *startPos,
2054 unsigned posLen) {
2055 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2056 getLocationOfByte(startPos),
2057 /*IsStringLocation*/true,
2058 getSpecifierRange(startPos, posLen));
2059}
2060
Ted Kremenekefaff192010-02-27 01:41:03 +00002061void
Ted Kremenek826a3452010-07-16 02:11:22 +00002062CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2063 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2065 << (unsigned) p,
2066 getLocationOfByte(startPos), /*IsStringLocation*/true,
2067 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002068}
2069
Ted Kremenek826a3452010-07-16 02:11:22 +00002070void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002071 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002072 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2073 getLocationOfByte(startPos),
2074 /*IsStringLocation*/true,
2075 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002076}
2077
Ted Kremenek826a3452010-07-16 02:11:22 +00002078void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002079 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002080 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002081 EmitFormatDiagnostic(
2082 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2083 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2084 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002085 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002086}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002087
Ted Kremenek826a3452010-07-16 02:11:22 +00002088const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002089 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002090}
2091
2092void CheckFormatHandler::DoneProcessing() {
2093 // Does the number of data arguments exceed the number of
2094 // format conversions in the format string?
2095 if (!HasVAListArg) {
2096 // Find any arguments that weren't covered.
2097 CoveredArgs.flip();
2098 signed notCoveredArg = CoveredArgs.find_first();
2099 if (notCoveredArg >= 0) {
2100 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002101 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
2102 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2103 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2104 Loc,
2105 /*IsStringLocation*/false, getFormatStringRange());
2106 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002107 }
2108 }
2109}
2110
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002111bool
2112CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2113 SourceLocation Loc,
2114 const char *startSpec,
2115 unsigned specifierLen,
2116 const char *csStart,
2117 unsigned csLen) {
2118
2119 bool keepGoing = true;
2120 if (argIndex < NumDataArgs) {
2121 // Consider the argument coverered, even though the specifier doesn't
2122 // make sense.
2123 CoveredArgs.set(argIndex);
2124 }
2125 else {
2126 // If argIndex exceeds the number of data arguments we
2127 // don't issue a warning because that is just a cascade of warnings (and
2128 // they may have intended '%%' anyway). We don't want to continue processing
2129 // the format string after this point, however, as we will like just get
2130 // gibberish when trying to match arguments.
2131 keepGoing = false;
2132 }
2133
Richard Trieu55733de2011-10-28 00:41:25 +00002134 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2135 << StringRef(csStart, csLen),
2136 Loc, /*IsStringLocation*/true,
2137 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002138
2139 return keepGoing;
2140}
2141
Richard Trieu55733de2011-10-28 00:41:25 +00002142void
2143CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2144 const char *startSpec,
2145 unsigned specifierLen) {
2146 EmitFormatDiagnostic(
2147 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2148 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2149}
2150
Ted Kremenek666a1972010-07-26 19:45:42 +00002151bool
2152CheckFormatHandler::CheckNumArgs(
2153 const analyze_format_string::FormatSpecifier &FS,
2154 const analyze_format_string::ConversionSpecifier &CS,
2155 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2156
2157 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002158 PartialDiagnostic PDiag = FS.usesPositionalArg()
2159 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2160 << (argIndex+1) << NumDataArgs)
2161 : S.PDiag(diag::warn_printf_insufficient_data_args);
2162 EmitFormatDiagnostic(
2163 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2164 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002165 return false;
2166 }
2167 return true;
2168}
2169
Richard Trieu55733de2011-10-28 00:41:25 +00002170template<typename Range>
2171void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2172 SourceLocation Loc,
2173 bool IsStringLocation,
2174 Range StringRange,
2175 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002176 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002177 Loc, IsStringLocation, StringRange, FixIt);
2178}
2179
2180/// \brief If the format string is not within the funcion call, emit a note
2181/// so that the function call and string are in diagnostic messages.
2182///
2183/// \param inFunctionCall if true, the format string is within the function
2184/// call and only one diagnostic message will be produced. Otherwise, an
2185/// extra note will be emitted pointing to location of the format string.
2186///
2187/// \param ArgumentExpr the expression that is passed as the format string
2188/// argument in the function call. Used for getting locations when two
2189/// diagnostics are emitted.
2190///
2191/// \param PDiag the callee should already have provided any strings for the
2192/// diagnostic message. This function only adds locations and fixits
2193/// to diagnostics.
2194///
2195/// \param Loc primary location for diagnostic. If two diagnostics are
2196/// required, one will be at Loc and a new SourceLocation will be created for
2197/// the other one.
2198///
2199/// \param IsStringLocation if true, Loc points to the format string should be
2200/// used for the note. Otherwise, Loc points to the argument list and will
2201/// be used with PDiag.
2202///
2203/// \param StringRange some or all of the string to highlight. This is
2204/// templated so it can accept either a CharSourceRange or a SourceRange.
2205///
2206/// \param Fixit optional fix it hint for the format string.
2207template<typename Range>
2208void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2209 const Expr *ArgumentExpr,
2210 PartialDiagnostic PDiag,
2211 SourceLocation Loc,
2212 bool IsStringLocation,
2213 Range StringRange,
2214 FixItHint FixIt) {
2215 if (InFunctionCall)
2216 S.Diag(Loc, PDiag) << StringRange << FixIt;
2217 else {
2218 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2219 << ArgumentExpr->getSourceRange();
2220 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2221 diag::note_format_string_defined)
2222 << StringRange << FixIt;
2223 }
2224}
2225
Ted Kremenek826a3452010-07-16 02:11:22 +00002226//===--- CHECK: Printf format string checking ------------------------------===//
2227
2228namespace {
2229class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002230 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002231public:
2232 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2233 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002234 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002235 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002236 Expr **Args, unsigned NumArgs,
2237 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002238 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002239 numDataArgs, beg, hasVAListArg, Args, NumArgs,
2240 formatIdx, inFunctionCall), ObjCContext(isObjC) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002241
2242
2243 bool HandleInvalidPrintfConversionSpecifier(
2244 const analyze_printf::PrintfSpecifier &FS,
2245 const char *startSpecifier,
2246 unsigned specifierLen);
2247
2248 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2249 const char *startSpecifier,
2250 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002251 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2252 const char *StartSpecifier,
2253 unsigned SpecifierLen,
2254 const Expr *E);
2255
Ted Kremenek826a3452010-07-16 02:11:22 +00002256 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2257 const char *startSpecifier, unsigned specifierLen);
2258 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2259 const analyze_printf::OptionalAmount &Amt,
2260 unsigned type,
2261 const char *startSpecifier, unsigned specifierLen);
2262 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2263 const analyze_printf::OptionalFlag &flag,
2264 const char *startSpecifier, unsigned specifierLen);
2265 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2266 const analyze_printf::OptionalFlag &ignoredFlag,
2267 const analyze_printf::OptionalFlag &flag,
2268 const char *startSpecifier, unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002269 bool checkForCStrMembers(const analyze_printf::ArgTypeResult &ATR,
2270 const Expr *E, const CharSourceRange &CSR);
2271
Ted Kremenek826a3452010-07-16 02:11:22 +00002272};
2273}
2274
2275bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2276 const analyze_printf::PrintfSpecifier &FS,
2277 const char *startSpecifier,
2278 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002279 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002280 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002281
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002282 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2283 getLocationOfByte(CS.getStart()),
2284 startSpecifier, specifierLen,
2285 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002286}
2287
Ted Kremenek826a3452010-07-16 02:11:22 +00002288bool CheckPrintfHandler::HandleAmount(
2289 const analyze_format_string::OptionalAmount &Amt,
2290 unsigned k, const char *startSpecifier,
2291 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002292
2293 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002294 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002295 unsigned argIndex = Amt.getArgIndex();
2296 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002297 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2298 << k,
2299 getLocationOfByte(Amt.getStart()),
2300 /*IsStringLocation*/true,
2301 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002302 // Don't do any more checking. We will just emit
2303 // spurious errors.
2304 return false;
2305 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002306
Ted Kremenek0d277352010-01-29 01:06:55 +00002307 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002308 // Although not in conformance with C99, we also allow the argument to be
2309 // an 'unsigned int' as that is a reasonably safe case. GCC also
2310 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002311 CoveredArgs.set(argIndex);
2312 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002313 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002314
2315 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2316 assert(ATR.isValid());
2317
2318 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002319 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002320 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002321 << T << Arg->getSourceRange(),
2322 getLocationOfByte(Amt.getStart()),
2323 /*IsStringLocation*/true,
2324 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002325 // Don't do any more checking. We will just emit
2326 // spurious errors.
2327 return false;
2328 }
2329 }
2330 }
2331 return true;
2332}
Ted Kremenek0d277352010-01-29 01:06:55 +00002333
Tom Caree4ee9662010-06-17 19:00:27 +00002334void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002335 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002336 const analyze_printf::OptionalAmount &Amt,
2337 unsigned type,
2338 const char *startSpecifier,
2339 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002340 const analyze_printf::PrintfConversionSpecifier &CS =
2341 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002342
Richard Trieu55733de2011-10-28 00:41:25 +00002343 FixItHint fixit =
2344 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2345 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2346 Amt.getConstantLength()))
2347 : FixItHint();
2348
2349 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2350 << type << CS.toString(),
2351 getLocationOfByte(Amt.getStart()),
2352 /*IsStringLocation*/true,
2353 getSpecifierRange(startSpecifier, specifierLen),
2354 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002355}
2356
Ted Kremenek826a3452010-07-16 02:11:22 +00002357void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002358 const analyze_printf::OptionalFlag &flag,
2359 const char *startSpecifier,
2360 unsigned specifierLen) {
2361 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002362 const analyze_printf::PrintfConversionSpecifier &CS =
2363 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002364 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2365 << flag.toString() << CS.toString(),
2366 getLocationOfByte(flag.getPosition()),
2367 /*IsStringLocation*/true,
2368 getSpecifierRange(startSpecifier, specifierLen),
2369 FixItHint::CreateRemoval(
2370 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002371}
2372
2373void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002374 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002375 const analyze_printf::OptionalFlag &ignoredFlag,
2376 const analyze_printf::OptionalFlag &flag,
2377 const char *startSpecifier,
2378 unsigned specifierLen) {
2379 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002380 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2381 << ignoredFlag.toString() << flag.toString(),
2382 getLocationOfByte(ignoredFlag.getPosition()),
2383 /*IsStringLocation*/true,
2384 getSpecifierRange(startSpecifier, specifierLen),
2385 FixItHint::CreateRemoval(
2386 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002387}
2388
Richard Smith831421f2012-06-25 20:30:08 +00002389// Determines if the specified is a C++ class or struct containing
2390// a member with the specified name and kind (e.g. a CXXMethodDecl named
2391// "c_str()").
2392template<typename MemberKind>
2393static llvm::SmallPtrSet<MemberKind*, 1>
2394CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2395 const RecordType *RT = Ty->getAs<RecordType>();
2396 llvm::SmallPtrSet<MemberKind*, 1> Results;
2397
2398 if (!RT)
2399 return Results;
2400 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2401 if (!RD)
2402 return Results;
2403
2404 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2405 Sema::LookupMemberName);
2406
2407 // We just need to include all members of the right kind turned up by the
2408 // filter, at this point.
2409 if (S.LookupQualifiedName(R, RT->getDecl()))
2410 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2411 NamedDecl *decl = (*I)->getUnderlyingDecl();
2412 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2413 Results.insert(FK);
2414 }
2415 return Results;
2416}
2417
2418// Check if a (w)string was passed when a (w)char* was needed, and offer a
2419// better diagnostic if so. ATR is assumed to be valid.
2420// Returns true when a c_str() conversion method is found.
2421bool CheckPrintfHandler::checkForCStrMembers(
2422 const analyze_printf::ArgTypeResult &ATR, const Expr *E,
2423 const CharSourceRange &CSR) {
2424 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2425
2426 MethodSet Results =
2427 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2428
2429 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2430 MI != ME; ++MI) {
2431 const CXXMethodDecl *Method = *MI;
2432 if (Method->getNumParams() == 0 &&
2433 ATR.matchesType(S.Context, Method->getResultType())) {
2434 // FIXME: Suggest parens if the expression needs them.
2435 SourceLocation EndLoc =
2436 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2437 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2438 << "c_str()"
2439 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2440 return true;
2441 }
2442 }
2443
2444 return false;
2445}
2446
Ted Kremeneke0e53132010-01-28 23:39:18 +00002447bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002448CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002449 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002450 const char *startSpecifier,
2451 unsigned specifierLen) {
2452
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002453 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002454 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002455 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002456
Ted Kremenekbaa40062010-07-19 22:01:06 +00002457 if (FS.consumesDataArgument()) {
2458 if (atFirstArg) {
2459 atFirstArg = false;
2460 usesPositionalArgs = FS.usesPositionalArg();
2461 }
2462 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002463 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2464 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002465 return false;
2466 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002467 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002468
Ted Kremenekefaff192010-02-27 01:41:03 +00002469 // First check if the field width, precision, and conversion specifier
2470 // have matching data arguments.
2471 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2472 startSpecifier, specifierLen)) {
2473 return false;
2474 }
2475
2476 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2477 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002478 return false;
2479 }
2480
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002481 if (!CS.consumesDataArgument()) {
2482 // FIXME: Technically specifying a precision or field width here
2483 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002484 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002485 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002486
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002487 // Consume the argument.
2488 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002489 if (argIndex < NumDataArgs) {
2490 // The check to see if the argIndex is valid will come later.
2491 // We set the bit here because we may exit early from this
2492 // function if we encounter some other error.
2493 CoveredArgs.set(argIndex);
2494 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002495
2496 // Check for using an Objective-C specific conversion specifier
2497 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002498 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002499 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2500 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002501 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002502
Tom Caree4ee9662010-06-17 19:00:27 +00002503 // Check for invalid use of field width
2504 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002505 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002506 startSpecifier, specifierLen);
2507 }
2508
2509 // Check for invalid use of precision
2510 if (!FS.hasValidPrecision()) {
2511 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2512 startSpecifier, specifierLen);
2513 }
2514
2515 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002516 if (!FS.hasValidThousandsGroupingPrefix())
2517 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002518 if (!FS.hasValidLeadingZeros())
2519 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2520 if (!FS.hasValidPlusPrefix())
2521 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002522 if (!FS.hasValidSpacePrefix())
2523 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002524 if (!FS.hasValidAlternativeForm())
2525 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2526 if (!FS.hasValidLeftJustified())
2527 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2528
2529 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002530 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2531 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2532 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002533 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2534 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2535 startSpecifier, specifierLen);
2536
2537 // Check the length modifier is valid with the given conversion specifier.
2538 const LengthModifier &LM = FS.getLengthModifier();
2539 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002540 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2541 << LM.toString() << CS.toString(),
2542 getLocationOfByte(LM.getStart()),
2543 /*IsStringLocation*/true,
2544 getSpecifierRange(startSpecifier, specifierLen),
2545 FixItHint::CreateRemoval(
2546 getSpecifierRange(LM.getStart(),
2547 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002548 if (!FS.hasStandardLengthModifier())
2549 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002550 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002551 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2552 if (!FS.hasStandardLengthConversionCombination())
2553 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2554 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002555
2556 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002557 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002558 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002559 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2560 getLocationOfByte(CS.getStart()),
2561 /*IsStringLocation*/true,
2562 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002563 // Continue checking the other format specifiers.
2564 return true;
2565 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002566
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002567 // The remaining checks depend on the data arguments.
2568 if (HasVAListArg)
2569 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002570
Ted Kremenek666a1972010-07-26 19:45:42 +00002571 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002572 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002573
Richard Smith831421f2012-06-25 20:30:08 +00002574 return checkFormatExpr(FS, startSpecifier, specifierLen,
2575 getDataArg(argIndex));
2576}
2577
2578bool
2579CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2580 const char *StartSpecifier,
2581 unsigned SpecifierLen,
2582 const Expr *E) {
2583 using namespace analyze_format_string;
2584 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002585 // Now type check the data expression that matches the
2586 // format specifier.
Nico Weber339b9072012-01-31 01:43:25 +00002587 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
Jordan Rose50687312012-06-04 23:52:23 +00002588 ObjCContext);
Richard Smith831421f2012-06-25 20:30:08 +00002589 if (ATR.isValid() && !ATR.matchesType(S.Context, E->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002590 // Look through argument promotions for our error message's reported type.
2591 // This includes the integral and floating promotions, but excludes array
2592 // and function pointer decay; seeing that an argument intended to be a
2593 // string has type 'char [6]' is probably more confusing than 'char *'.
Richard Smith831421f2012-06-25 20:30:08 +00002594 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002595 if (ICE->getCastKind() == CK_IntegralCast ||
2596 ICE->getCastKind() == CK_FloatingCast) {
Richard Smith831421f2012-06-25 20:30:08 +00002597 E = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002598
2599 // Check if we didn't match because of an implicit cast from a 'char'
2600 // or 'short' to an 'int'. This is done because printf is a varargs
2601 // function.
2602 if (ICE->getType() == S.Context.IntTy ||
2603 ICE->getType() == S.Context.UnsignedIntTy) {
2604 // All further checking is done on the subexpression.
Richard Smith831421f2012-06-25 20:30:08 +00002605 if (ATR.matchesType(S.Context, E->getType()))
Jordan Roseee0259d2012-06-04 22:48:57 +00002606 return true;
2607 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002608 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002609 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002610
2611 // We may be able to offer a FixItHint if it is a supported type.
2612 PrintfSpecifier fixedFS = FS;
Richard Smith831421f2012-06-25 20:30:08 +00002613 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002614 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002615
2616 if (success) {
2617 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002618 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002619 llvm::raw_svector_ostream os(buf);
2620 fixedFS.toString(os);
2621
Richard Trieu55733de2011-10-28 00:41:25 +00002622 EmitFormatDiagnostic(
2623 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Richard Smith831421f2012-06-25 20:30:08 +00002624 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2625 << E->getSourceRange(),
2626 E->getLocStart(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002627 /*IsStringLocation*/false,
Richard Smith831421f2012-06-25 20:30:08 +00002628 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002629 FixItHint::CreateReplacement(
Richard Smith831421f2012-06-25 20:30:08 +00002630 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002631 os.str()));
Richard Smith831421f2012-06-25 20:30:08 +00002632 } else {
2633 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2634 SpecifierLen);
2635 // Since the warning for passing non-POD types to variadic functions
2636 // was deferred until now, we emit a warning for non-POD
2637 // arguments here.
2638 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2639 EmitFormatDiagnostic(
2640 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
2641 << S.getLangOpts().CPlusPlus0x
2642 << E->getType()
2643 << ATR.getRepresentativeTypeName(S.Context)
2644 << CSR
2645 << E->getSourceRange(),
2646 E->getLocStart(), /*IsStringLocation*/false, CSR);
2647
2648 checkForCStrMembers(ATR, E, CSR);
2649 } else
2650 EmitFormatDiagnostic(
2651 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2652 << ATR.getRepresentativeTypeName(S.Context) << E->getType()
2653 << CSR
2654 << E->getSourceRange(),
2655 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002656 }
2657 }
2658
Ted Kremeneke0e53132010-01-28 23:39:18 +00002659 return true;
2660}
2661
Ted Kremenek826a3452010-07-16 02:11:22 +00002662//===--- CHECK: Scanf format string checking ------------------------------===//
2663
2664namespace {
2665class CheckScanfHandler : public CheckFormatHandler {
2666public:
2667 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2668 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002669 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002670 Expr **Args, unsigned NumArgs,
2671 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002672 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002673 numDataArgs, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002674 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002675
2676 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2677 const char *startSpecifier,
2678 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002679
2680 bool HandleInvalidScanfConversionSpecifier(
2681 const analyze_scanf::ScanfSpecifier &FS,
2682 const char *startSpecifier,
2683 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002684
2685 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002686};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002687}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002688
Ted Kremenekb7c21012010-07-16 18:28:03 +00002689void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2690 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002691 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2692 getLocationOfByte(end), /*IsStringLocation*/true,
2693 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002694}
2695
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002696bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2697 const analyze_scanf::ScanfSpecifier &FS,
2698 const char *startSpecifier,
2699 unsigned specifierLen) {
2700
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002701 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002702 FS.getConversionSpecifier();
2703
2704 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2705 getLocationOfByte(CS.getStart()),
2706 startSpecifier, specifierLen,
2707 CS.getStart(), CS.getLength());
2708}
2709
Ted Kremenek826a3452010-07-16 02:11:22 +00002710bool CheckScanfHandler::HandleScanfSpecifier(
2711 const analyze_scanf::ScanfSpecifier &FS,
2712 const char *startSpecifier,
2713 unsigned specifierLen) {
2714
2715 using namespace analyze_scanf;
2716 using namespace analyze_format_string;
2717
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002718 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002719
Ted Kremenekbaa40062010-07-19 22:01:06 +00002720 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2721 // be used to decide if we are using positional arguments consistently.
2722 if (FS.consumesDataArgument()) {
2723 if (atFirstArg) {
2724 atFirstArg = false;
2725 usesPositionalArgs = FS.usesPositionalArg();
2726 }
2727 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002728 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2729 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002730 return false;
2731 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002732 }
2733
2734 // Check if the field with is non-zero.
2735 const OptionalAmount &Amt = FS.getFieldWidth();
2736 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2737 if (Amt.getConstantAmount() == 0) {
2738 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2739 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002740 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2741 getLocationOfByte(Amt.getStart()),
2742 /*IsStringLocation*/true, R,
2743 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002744 }
2745 }
2746
2747 if (!FS.consumesDataArgument()) {
2748 // FIXME: Technically specifying a precision or field width here
2749 // makes no sense. Worth issuing a warning at some point.
2750 return true;
2751 }
2752
2753 // Consume the argument.
2754 unsigned argIndex = FS.getArgIndex();
2755 if (argIndex < NumDataArgs) {
2756 // The check to see if the argIndex is valid will come later.
2757 // We set the bit here because we may exit early from this
2758 // function if we encounter some other error.
2759 CoveredArgs.set(argIndex);
2760 }
2761
Ted Kremenek1e51c202010-07-20 20:04:47 +00002762 // Check the length modifier is valid with the given conversion specifier.
2763 const LengthModifier &LM = FS.getLengthModifier();
2764 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002765 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2766 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2767 << LM.toString() << CS.toString()
2768 << getSpecifierRange(startSpecifier, specifierLen),
2769 getLocationOfByte(LM.getStart()),
2770 /*IsStringLocation*/true, R,
2771 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002772 }
2773
Hans Wennborg76517422012-02-22 10:17:01 +00002774 if (!FS.hasStandardLengthModifier())
2775 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002776 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002777 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2778 if (!FS.hasStandardLengthConversionCombination())
2779 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2780 specifierLen);
2781
Ted Kremenek826a3452010-07-16 02:11:22 +00002782 // The remaining checks depend on the data arguments.
2783 if (HasVAListArg)
2784 return true;
2785
Ted Kremenek666a1972010-07-26 19:45:42 +00002786 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002787 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002788
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002789 // Check that the argument type matches the format specifier.
2790 const Expr *Ex = getDataArg(argIndex);
2791 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2792 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2793 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002794 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002795 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002796
2797 if (success) {
2798 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002799 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002800 llvm::raw_svector_ostream os(buf);
2801 fixedFS.toString(os);
2802
2803 EmitFormatDiagnostic(
2804 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2805 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2806 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002807 Ex->getLocStart(),
2808 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002809 getSpecifierRange(startSpecifier, specifierLen),
2810 FixItHint::CreateReplacement(
2811 getSpecifierRange(startSpecifier, specifierLen),
2812 os.str()));
2813 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002814 EmitFormatDiagnostic(
2815 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002816 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002817 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002818 Ex->getLocStart(),
2819 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002820 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002821 }
2822 }
2823
Ted Kremenek826a3452010-07-16 02:11:22 +00002824 return true;
2825}
2826
2827void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002828 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002829 Expr **Args, unsigned NumArgs,
2830 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002831 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002832 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002833
Ted Kremeneke0e53132010-01-28 23:39:18 +00002834 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002835 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002836 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002837 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002838 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2839 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002840 return;
2841 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002842
Ted Kremeneke0e53132010-01-28 23:39:18 +00002843 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002844 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002845 const char *Str = StrRef.data();
2846 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002847 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002848
Ted Kremeneke0e53132010-01-28 23:39:18 +00002849 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002850 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002851 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002852 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002853 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2854 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002855 return;
2856 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002857
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002858 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002859 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002860 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002861 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002862 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002863
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002864 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002865 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002866 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002867 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002868 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002869 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002870 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002871
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002872 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002873 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002874 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002875 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002876}
2877
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002878//===--- CHECK: Standard memory functions ---------------------------------===//
2879
Douglas Gregor2a053a32011-05-03 20:05:22 +00002880/// \brief Determine whether the given type is a dynamic class type (e.g.,
2881/// whether it has a vtable).
2882static bool isDynamicClassType(QualType T) {
2883 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2884 if (CXXRecordDecl *Definition = Record->getDefinition())
2885 if (Definition->isDynamicClass())
2886 return true;
2887
2888 return false;
2889}
2890
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002891/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002892/// otherwise returns NULL.
2893static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002894 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002895 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2896 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2897 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002898
Chandler Carruth000d4282011-06-16 09:09:40 +00002899 return 0;
2900}
2901
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002902/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002903static QualType getSizeOfArgType(const Expr* E) {
2904 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2905 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2906 if (SizeOf->getKind() == clang::UETT_SizeOf)
2907 return SizeOf->getTypeOfArgument();
2908
2909 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002910}
2911
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002912/// \brief Check for dangerous or invalid arguments to memset().
2913///
Chandler Carruth929f0132011-06-03 06:23:57 +00002914/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002915/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2916/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002917///
2918/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002919void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002920 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002921 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002922 assert(BId != 0);
2923
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002924 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002925 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002926 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002927 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002928 return;
2929
Anna Zaks0a151a12012-01-17 00:37:07 +00002930 unsigned LastArg = (BId == Builtin::BImemset ||
2931 BId == Builtin::BIstrndup ? 1 : 2);
2932 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002933 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002934
2935 // We have special checking when the length is a sizeof expression.
2936 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2937 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2938 llvm::FoldingSetNodeID SizeOfArgID;
2939
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002940 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2941 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002942 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002943
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002944 QualType DestTy = Dest->getType();
2945 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2946 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002947
Chandler Carruth000d4282011-06-16 09:09:40 +00002948 // Never warn about void type pointers. This can be used to suppress
2949 // false positives.
2950 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002951 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002952
Chandler Carruth000d4282011-06-16 09:09:40 +00002953 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2954 // actually comparing the expressions for equality. Because computing the
2955 // expression IDs can be expensive, we only do this if the diagnostic is
2956 // enabled.
2957 if (SizeOfArg &&
2958 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2959 SizeOfArg->getExprLoc())) {
2960 // We only compute IDs for expressions if the warning is enabled, and
2961 // cache the sizeof arg's ID.
2962 if (SizeOfArgID == llvm::FoldingSetNodeID())
2963 SizeOfArg->Profile(SizeOfArgID, Context, true);
2964 llvm::FoldingSetNodeID DestID;
2965 Dest->Profile(DestID, Context, true);
2966 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002967 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2968 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002969 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002970 StringRef ReadableName = FnName->getName();
2971
Chandler Carruth000d4282011-06-16 09:09:40 +00002972 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002973 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002974 ActionIdx = 1; // If its an address-of operator, just remove it.
2975 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2976 ActionIdx = 2; // If the pointee's size is sizeof(char),
2977 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002978
2979 // If the function is defined as a builtin macro, do not show macro
2980 // expansion.
2981 SourceLocation SL = SizeOfArg->getExprLoc();
2982 SourceRange DSR = Dest->getSourceRange();
2983 SourceRange SSR = SizeOfArg->getSourceRange();
2984 SourceManager &SM = PP.getSourceManager();
2985
2986 if (SM.isMacroArgExpansion(SL)) {
2987 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
2988 SL = SM.getSpellingLoc(SL);
2989 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
2990 SM.getSpellingLoc(DSR.getEnd()));
2991 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
2992 SM.getSpellingLoc(SSR.getEnd()));
2993 }
2994
Anna Zaks90c78322012-05-30 23:14:52 +00002995 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00002996 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00002997 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00002998 << PointeeTy
2999 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003000 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003001 << SSR);
3002 DiagRuntimeBehavior(SL, SizeOfArg,
3003 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3004 << ActionIdx
3005 << SSR);
3006
Chandler Carruth000d4282011-06-16 09:09:40 +00003007 break;
3008 }
3009 }
3010
3011 // Also check for cases where the sizeof argument is the exact same
3012 // type as the memory argument, and where it points to a user-defined
3013 // record type.
3014 if (SizeOfArgTy != QualType()) {
3015 if (PointeeTy->isRecordType() &&
3016 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3017 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3018 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3019 << FnName << SizeOfArgTy << ArgIdx
3020 << PointeeTy << Dest->getSourceRange()
3021 << LenExpr->getSourceRange());
3022 break;
3023 }
Nico Webere4a1c642011-06-14 16:14:58 +00003024 }
3025
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003026 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003027 if (isDynamicClassType(PointeeTy)) {
3028
3029 unsigned OperationType = 0;
3030 // "overwritten" if we're warning about the destination for any call
3031 // but memcmp; otherwise a verb appropriate to the call.
3032 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3033 if (BId == Builtin::BImemcpy)
3034 OperationType = 1;
3035 else if(BId == Builtin::BImemmove)
3036 OperationType = 2;
3037 else if (BId == Builtin::BImemcmp)
3038 OperationType = 3;
3039 }
3040
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003041 DiagRuntimeBehavior(
3042 Dest->getExprLoc(), Dest,
3043 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003044 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003045 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003046 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003047 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003048 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3049 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003050 DiagRuntimeBehavior(
3051 Dest->getExprLoc(), Dest,
3052 PDiag(diag::warn_arc_object_memaccess)
3053 << ArgIdx << FnName << PointeeTy
3054 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003055 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003056 continue;
John McCallf85e1932011-06-15 23:02:42 +00003057
3058 DiagRuntimeBehavior(
3059 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003060 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003061 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3062 break;
3063 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003064 }
3065}
3066
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003067// A little helper routine: ignore addition and subtraction of integer literals.
3068// This intentionally does not ignore all integer constant expressions because
3069// we don't want to remove sizeof().
3070static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3071 Ex = Ex->IgnoreParenCasts();
3072
3073 for (;;) {
3074 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3075 if (!BO || !BO->isAdditiveOp())
3076 break;
3077
3078 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3079 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3080
3081 if (isa<IntegerLiteral>(RHS))
3082 Ex = LHS;
3083 else if (isa<IntegerLiteral>(LHS))
3084 Ex = RHS;
3085 else
3086 break;
3087 }
3088
3089 return Ex;
3090}
3091
3092// Warn if the user has made the 'size' argument to strlcpy or strlcat
3093// be the size of the source, instead of the destination.
3094void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3095 IdentifierInfo *FnName) {
3096
3097 // Don't crash if the user has the wrong number of arguments
3098 if (Call->getNumArgs() != 3)
3099 return;
3100
3101 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3102 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3103 const Expr *CompareWithSrc = NULL;
3104
3105 // Look for 'strlcpy(dst, x, sizeof(x))'
3106 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3107 CompareWithSrc = Ex;
3108 else {
3109 // Look for 'strlcpy(dst, x, strlen(x))'
3110 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003111 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003112 && SizeCall->getNumArgs() == 1)
3113 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3114 }
3115 }
3116
3117 if (!CompareWithSrc)
3118 return;
3119
3120 // Determine if the argument to sizeof/strlen is equal to the source
3121 // argument. In principle there's all kinds of things you could do
3122 // here, for instance creating an == expression and evaluating it with
3123 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3124 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3125 if (!SrcArgDRE)
3126 return;
3127
3128 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3129 if (!CompareWithSrcDRE ||
3130 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3131 return;
3132
3133 const Expr *OriginalSizeArg = Call->getArg(2);
3134 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3135 << OriginalSizeArg->getSourceRange() << FnName;
3136
3137 // Output a FIXIT hint if the destination is an array (rather than a
3138 // pointer to an array). This could be enhanced to handle some
3139 // pointers if we know the actual size, like if DstArg is 'array+2'
3140 // we could say 'sizeof(array)-2'.
3141 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00003142 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003143
Ted Kremenek8f746222011-08-18 22:48:41 +00003144 // Only handle constant-sized or VLAs, but not flexible members.
3145 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3146 // Only issue the FIXIT for arrays of size > 1.
3147 if (CAT->getSize().getSExtValue() <= 1)
3148 return;
3149 } else if (!DstArgTy->isVariableArrayType()) {
3150 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003151 }
Ted Kremenek8f746222011-08-18 22:48:41 +00003152
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003153 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003154 llvm::raw_svector_ostream OS(sizeString);
3155 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00003156 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003157 OS << ")";
3158
3159 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3160 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3161 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003162}
3163
Anna Zaksc36bedc2012-02-01 19:08:57 +00003164/// Check if two expressions refer to the same declaration.
3165static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3166 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3167 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3168 return D1->getDecl() == D2->getDecl();
3169 return false;
3170}
3171
3172static const Expr *getStrlenExprArg(const Expr *E) {
3173 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3174 const FunctionDecl *FD = CE->getDirectCallee();
3175 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3176 return 0;
3177 return CE->getArg(0)->IgnoreParenCasts();
3178 }
3179 return 0;
3180}
3181
3182// Warn on anti-patterns as the 'size' argument to strncat.
3183// The correct size argument should look like following:
3184// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3185void Sema::CheckStrncatArguments(const CallExpr *CE,
3186 IdentifierInfo *FnName) {
3187 // Don't crash if the user has the wrong number of arguments.
3188 if (CE->getNumArgs() < 3)
3189 return;
3190 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3191 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3192 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3193
3194 // Identify common expressions, which are wrongly used as the size argument
3195 // to strncat and may lead to buffer overflows.
3196 unsigned PatternType = 0;
3197 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3198 // - sizeof(dst)
3199 if (referToTheSameDecl(SizeOfArg, DstArg))
3200 PatternType = 1;
3201 // - sizeof(src)
3202 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3203 PatternType = 2;
3204 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3205 if (BE->getOpcode() == BO_Sub) {
3206 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3207 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3208 // - sizeof(dst) - strlen(dst)
3209 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3210 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3211 PatternType = 1;
3212 // - sizeof(src) - (anything)
3213 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3214 PatternType = 2;
3215 }
3216 }
3217
3218 if (PatternType == 0)
3219 return;
3220
Anna Zaksafdb0412012-02-03 01:27:37 +00003221 // Generate the diagnostic.
3222 SourceLocation SL = LenArg->getLocStart();
3223 SourceRange SR = LenArg->getSourceRange();
3224 SourceManager &SM = PP.getSourceManager();
3225
3226 // If the function is defined as a builtin macro, do not show macro expansion.
3227 if (SM.isMacroArgExpansion(SL)) {
3228 SL = SM.getSpellingLoc(SL);
3229 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3230 SM.getSpellingLoc(SR.getEnd()));
3231 }
3232
Anna Zaksc36bedc2012-02-01 19:08:57 +00003233 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003234 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003235 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003236 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003237
3238 // Output a FIXIT hint if the destination is an array (rather than a
3239 // pointer to an array). This could be enhanced to handle some
3240 // pointers if we know the actual size, like if DstArg is 'array+2'
3241 // we could say 'sizeof(array)-2'.
3242 QualType DstArgTy = DstArg->getType();
3243
3244 // Only handle constant-sized or VLAs, but not flexible members.
3245 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3246 // Only issue the FIXIT for arrays of size > 1.
3247 if (CAT->getSize().getSExtValue() <= 1)
3248 return;
3249 } else if (!DstArgTy->isVariableArrayType()) {
3250 return;
3251 }
3252
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003253 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003254 llvm::raw_svector_ostream OS(sizeString);
3255 OS << "sizeof(";
3256 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3257 OS << ") - ";
3258 OS << "strlen(";
3259 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3260 OS << ") - 1";
3261
Anna Zaksafdb0412012-02-03 01:27:37 +00003262 Diag(SL, diag::note_strncat_wrong_size)
3263 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003264}
3265
Ted Kremenek06de2762007-08-17 16:46:58 +00003266//===--- CHECK: Return Address of Stack Variable --------------------------===//
3267
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003268static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3269 Decl *ParentDecl);
3270static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3271 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003272
3273/// CheckReturnStackAddr - Check if a return statement returns the address
3274/// of a stack variable.
3275void
3276Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3277 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003279 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003280 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003281
3282 // Perform checking for returned stack addresses, local blocks,
3283 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003284 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003285 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003286 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003287 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003288 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003289 }
3290
3291 if (stackE == 0)
3292 return; // Nothing suspicious was found.
3293
3294 SourceLocation diagLoc;
3295 SourceRange diagRange;
3296 if (refVars.empty()) {
3297 diagLoc = stackE->getLocStart();
3298 diagRange = stackE->getSourceRange();
3299 } else {
3300 // We followed through a reference variable. 'stackE' contains the
3301 // problematic expression but we will warn at the return statement pointing
3302 // at the reference variable. We will later display the "trail" of
3303 // reference variables using notes.
3304 diagLoc = refVars[0]->getLocStart();
3305 diagRange = refVars[0]->getSourceRange();
3306 }
3307
3308 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3309 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3310 : diag::warn_ret_stack_addr)
3311 << DR->getDecl()->getDeclName() << diagRange;
3312 } else if (isa<BlockExpr>(stackE)) { // local block.
3313 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3314 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3315 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3316 } else { // local temporary.
3317 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3318 : diag::warn_ret_local_temp_addr)
3319 << diagRange;
3320 }
3321
3322 // Display the "trail" of reference variables that we followed until we
3323 // found the problematic expression using notes.
3324 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3325 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3326 // If this var binds to another reference var, show the range of the next
3327 // var, otherwise the var binds to the problematic expression, in which case
3328 // show the range of the expression.
3329 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3330 : stackE->getSourceRange();
3331 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3332 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003333 }
3334}
3335
3336/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3337/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003338/// to a location on the stack, a local block, an address of a label, or a
3339/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003340/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003341/// encounter a subexpression that (1) clearly does not lead to one of the
3342/// above problematic expressions (2) is something we cannot determine leads to
3343/// a problematic expression based on such local checking.
3344///
3345/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3346/// the expression that they point to. Such variables are added to the
3347/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003348///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003349/// EvalAddr processes expressions that are pointers that are used as
3350/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003351/// At the base case of the recursion is a check for the above problematic
3352/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003353///
3354/// This implementation handles:
3355///
3356/// * pointer-to-pointer casts
3357/// * implicit conversions from array references to pointers
3358/// * taking the address of fields
3359/// * arbitrary interplay between "&" and "*" operators
3360/// * pointer arithmetic from an address of a stack variable
3361/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003362static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3363 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003364 if (E->isTypeDependent())
3365 return NULL;
3366
Ted Kremenek06de2762007-08-17 16:46:58 +00003367 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003368 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003369 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003370 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003371 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Peter Collingbournef111d932011-04-15 00:35:48 +00003373 E = E->IgnoreParens();
3374
Ted Kremenek06de2762007-08-17 16:46:58 +00003375 // Our "symbolic interpreter" is just a dispatch off the currently
3376 // viewed AST node. We then recursively traverse the AST by calling
3377 // EvalAddr and EvalVal appropriately.
3378 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003379 case Stmt::DeclRefExprClass: {
3380 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3381
3382 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3383 // If this is a reference variable, follow through to the expression that
3384 // it points to.
3385 if (V->hasLocalStorage() &&
3386 V->getType()->isReferenceType() && V->hasInit()) {
3387 // Add the reference variable to the "trail".
3388 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003389 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003390 }
3391
3392 return NULL;
3393 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003394
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003395 case Stmt::UnaryOperatorClass: {
3396 // The only unary operator that make sense to handle here
3397 // is AddrOf. All others don't make sense as pointers.
3398 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCall2de56d12010-08-25 11:45:40 +00003400 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003401 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003402 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003403 return NULL;
3404 }
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003406 case Stmt::BinaryOperatorClass: {
3407 // Handle pointer arithmetic. All other binary operators are not valid
3408 // in this context.
3409 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003410 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003411
John McCall2de56d12010-08-25 11:45:40 +00003412 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003413 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003415 Expr *Base = B->getLHS();
3416
3417 // Determine which argument is the real pointer base. It could be
3418 // the RHS argument instead of the LHS.
3419 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003421 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003422 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003423 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003424
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003425 // For conditional operators we need to see if either the LHS or RHS are
3426 // valid DeclRefExpr*s. If one of them is valid, we return it.
3427 case Stmt::ConditionalOperatorClass: {
3428 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003430 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003431 if (Expr *lhsExpr = C->getLHS()) {
3432 // In C++, we can have a throw-expression, which has 'void' type.
3433 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003434 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003435 return LHS;
3436 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003437
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003438 // In C++, we can have a throw-expression, which has 'void' type.
3439 if (C->getRHS()->getType()->isVoidType())
3440 return NULL;
3441
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003442 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003443 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003444
3445 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003446 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003447 return E; // local block.
3448 return NULL;
3449
3450 case Stmt::AddrLabelExprClass:
3451 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003452
John McCall80ee6e82011-11-10 05:35:25 +00003453 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003454 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3455 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003456
Ted Kremenek54b52742008-08-07 00:49:01 +00003457 // For casts, we need to handle conversions from arrays to
3458 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003459 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003460 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003461 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003462 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003463 case Stmt::CXXStaticCastExprClass:
3464 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003465 case Stmt::CXXConstCastExprClass:
3466 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003467 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3468 switch (cast<CastExpr>(E)->getCastKind()) {
3469 case CK_BitCast:
3470 case CK_LValueToRValue:
3471 case CK_NoOp:
3472 case CK_BaseToDerived:
3473 case CK_DerivedToBase:
3474 case CK_UncheckedDerivedToBase:
3475 case CK_Dynamic:
3476 case CK_CPointerToObjCPointerCast:
3477 case CK_BlockPointerToObjCPointerCast:
3478 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003479 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003480
3481 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003482 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003483
3484 default:
3485 return 0;
3486 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003487 }
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregor03e80032011-06-21 17:03:29 +00003489 case Stmt::MaterializeTemporaryExprClass:
3490 if (Expr *Result = EvalAddr(
3491 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003492 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003493 return Result;
3494
3495 return E;
3496
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003497 // Everything else: we simply don't reason about them.
3498 default:
3499 return NULL;
3500 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003501}
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Ted Kremenek06de2762007-08-17 16:46:58 +00003503
3504/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3505/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003506static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3507 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003508do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003509 // We should only be called for evaluating non-pointer expressions, or
3510 // expressions with a pointer type that are not used as references but instead
3511 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Ted Kremenek06de2762007-08-17 16:46:58 +00003513 // Our "symbolic interpreter" is just a dispatch off the currently
3514 // viewed AST node. We then recursively traverse the AST by calling
3515 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003516
3517 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003518 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003519 case Stmt::ImplicitCastExprClass: {
3520 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003521 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003522 E = IE->getSubExpr();
3523 continue;
3524 }
3525 return NULL;
3526 }
3527
John McCall80ee6e82011-11-10 05:35:25 +00003528 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003529 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003530
Douglas Gregora2813ce2009-10-23 18:54:35 +00003531 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003532 // When we hit a DeclRefExpr we are looking at code that refers to a
3533 // variable's name. If it's not a reference variable we check if it has
3534 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003535 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003537 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3538 // Check if it refers to itself, e.g. "int& i = i;".
3539 if (V == ParentDecl)
3540 return DR;
3541
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003542 if (V->hasLocalStorage()) {
3543 if (!V->getType()->isReferenceType())
3544 return DR;
3545
3546 // Reference variable, follow through to the expression that
3547 // it points to.
3548 if (V->hasInit()) {
3549 // Add the reference variable to the "trail".
3550 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003551 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003552 }
3553 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003554 }
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Ted Kremenek06de2762007-08-17 16:46:58 +00003556 return NULL;
3557 }
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Ted Kremenek06de2762007-08-17 16:46:58 +00003559 case Stmt::UnaryOperatorClass: {
3560 // The only unary operator that make sense to handle here
3561 // is Deref. All others don't resolve to a "name." This includes
3562 // handling all sorts of rvalues passed to a unary operator.
3563 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCall2de56d12010-08-25 11:45:40 +00003565 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003566 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003567
3568 return NULL;
3569 }
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Ted Kremenek06de2762007-08-17 16:46:58 +00003571 case Stmt::ArraySubscriptExprClass: {
3572 // Array subscripts are potential references to data on the stack. We
3573 // retrieve the DeclRefExpr* for the array variable if it indeed
3574 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003575 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003576 }
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Ted Kremenek06de2762007-08-17 16:46:58 +00003578 case Stmt::ConditionalOperatorClass: {
3579 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003580 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003581 ConditionalOperator *C = cast<ConditionalOperator>(E);
3582
Anders Carlsson39073232007-11-30 19:04:31 +00003583 // Handle the GNU extension for missing LHS.
3584 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003585 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003586 return LHS;
3587
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003588 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003589 }
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Ted Kremenek06de2762007-08-17 16:46:58 +00003591 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003592 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003593 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Ted Kremenek06de2762007-08-17 16:46:58 +00003595 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003596 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003597 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003598
3599 // Check whether the member type is itself a reference, in which case
3600 // we're not going to refer to the member, but to what the member refers to.
3601 if (M->getMemberDecl()->getType()->isReferenceType())
3602 return NULL;
3603
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003604 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003605 }
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Douglas Gregor03e80032011-06-21 17:03:29 +00003607 case Stmt::MaterializeTemporaryExprClass:
3608 if (Expr *Result = EvalVal(
3609 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003610 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003611 return Result;
3612
3613 return E;
3614
Ted Kremenek06de2762007-08-17 16:46:58 +00003615 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003616 // Check that we don't return or take the address of a reference to a
3617 // temporary. This is only useful in C++.
3618 if (!E->isTypeDependent() && E->isRValue())
3619 return E;
3620
3621 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003622 return NULL;
3623 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003624} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003625}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003626
3627//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3628
3629/// Check for comparisons of floating point operands using != and ==.
3630/// Issue a warning if these are no self-comparisons, as they are not likely
3631/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003632void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003633 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Richard Trieudd225092011-09-15 21:56:47 +00003635 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3636 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003637
3638 // Special case: check for x == x (which is OK).
3639 // Do not emit warnings for such cases.
3640 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3641 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3642 if (DRL->getDecl() == DRR->getDecl())
3643 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003644
3645
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003646 // Special case: check for comparisons against literals that can be exactly
3647 // represented by APFloat. In such cases, do not emit a warning. This
3648 // is a heuristic: often comparison against such literals are used to
3649 // detect if a value in a variable has not changed. This clearly can
3650 // lead to false negatives.
3651 if (EmitWarning) {
3652 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3653 if (FLL->isExact())
3654 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003655 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003656 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3657 if (FLR->isExact())
3658 EmitWarning = false;
3659 }
3660 }
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003662 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003663 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003664 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003665 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003666 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Sebastian Redl0eb23302009-01-19 00:08:26 +00003668 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003669 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003670 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003671 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003673 // Emit the diagnostic.
3674 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003675 Diag(Loc, diag::warn_floatingpoint_eq)
3676 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003677}
John McCallba26e582010-01-04 23:21:16 +00003678
John McCallf2370c92010-01-06 05:24:50 +00003679//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3680//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003681
John McCallf2370c92010-01-06 05:24:50 +00003682namespace {
John McCallba26e582010-01-04 23:21:16 +00003683
John McCallf2370c92010-01-06 05:24:50 +00003684/// Structure recording the 'active' range of an integer-valued
3685/// expression.
3686struct IntRange {
3687 /// The number of bits active in the int.
3688 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003689
John McCallf2370c92010-01-06 05:24:50 +00003690 /// True if the int is known not to have negative values.
3691 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003692
John McCallf2370c92010-01-06 05:24:50 +00003693 IntRange(unsigned Width, bool NonNegative)
3694 : Width(Width), NonNegative(NonNegative)
3695 {}
John McCallba26e582010-01-04 23:21:16 +00003696
John McCall1844a6e2010-11-10 23:38:19 +00003697 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003698 static IntRange forBoolType() {
3699 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003700 }
3701
John McCall1844a6e2010-11-10 23:38:19 +00003702 /// Returns the range of an opaque value of the given integral type.
3703 static IntRange forValueOfType(ASTContext &C, QualType T) {
3704 return forValueOfCanonicalType(C,
3705 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003706 }
3707
John McCall1844a6e2010-11-10 23:38:19 +00003708 /// Returns the range of an opaque value of a canonical integral type.
3709 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003710 assert(T->isCanonicalUnqualified());
3711
3712 if (const VectorType *VT = dyn_cast<VectorType>(T))
3713 T = VT->getElementType().getTypePtr();
3714 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3715 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003716
John McCall091f23f2010-11-09 22:22:12 +00003717 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003718 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3719 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003720 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003721 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3722
John McCall323ed742010-05-06 08:58:33 +00003723 unsigned NumPositive = Enum->getNumPositiveBits();
3724 unsigned NumNegative = Enum->getNumNegativeBits();
3725
3726 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3727 }
John McCallf2370c92010-01-06 05:24:50 +00003728
3729 const BuiltinType *BT = cast<BuiltinType>(T);
3730 assert(BT->isInteger());
3731
3732 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3733 }
3734
John McCall1844a6e2010-11-10 23:38:19 +00003735 /// Returns the "target" range of a canonical integral type, i.e.
3736 /// the range of values expressible in the type.
3737 ///
3738 /// This matches forValueOfCanonicalType except that enums have the
3739 /// full range of their type, not the range of their enumerators.
3740 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3741 assert(T->isCanonicalUnqualified());
3742
3743 if (const VectorType *VT = dyn_cast<VectorType>(T))
3744 T = VT->getElementType().getTypePtr();
3745 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3746 T = CT->getElementType().getTypePtr();
3747 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003748 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003749
3750 const BuiltinType *BT = cast<BuiltinType>(T);
3751 assert(BT->isInteger());
3752
3753 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3754 }
3755
3756 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003757 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003758 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003759 L.NonNegative && R.NonNegative);
3760 }
3761
John McCall1844a6e2010-11-10 23:38:19 +00003762 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003763 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003764 return IntRange(std::min(L.Width, R.Width),
3765 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003766 }
3767};
3768
Ted Kremenek0692a192012-01-31 05:37:37 +00003769static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3770 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003771 if (value.isSigned() && value.isNegative())
3772 return IntRange(value.getMinSignedBits(), false);
3773
3774 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003775 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003776
3777 // isNonNegative() just checks the sign bit without considering
3778 // signedness.
3779 return IntRange(value.getActiveBits(), true);
3780}
3781
Ted Kremenek0692a192012-01-31 05:37:37 +00003782static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3783 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003784 if (result.isInt())
3785 return GetValueRange(C, result.getInt(), MaxWidth);
3786
3787 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003788 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3789 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3790 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3791 R = IntRange::join(R, El);
3792 }
John McCallf2370c92010-01-06 05:24:50 +00003793 return R;
3794 }
3795
3796 if (result.isComplexInt()) {
3797 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3798 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3799 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003800 }
3801
3802 // This can happen with lossless casts to intptr_t of "based" lvalues.
3803 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003804 // FIXME: The only reason we need to pass the type in here is to get
3805 // the sign right on this one case. It would be nice if APValue
3806 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003807 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003808 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003809}
John McCallf2370c92010-01-06 05:24:50 +00003810
3811/// Pseudo-evaluate the given integer expression, estimating the
3812/// range of values it might take.
3813///
3814/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003815static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003816 E = E->IgnoreParens();
3817
3818 // Try a full evaluation first.
3819 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003820 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003821 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003822
3823 // I think we only want to look through implicit casts here; if the
3824 // user has an explicit widening cast, we should treat the value as
3825 // being of the new, wider type.
3826 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003827 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003828 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3829
John McCall1844a6e2010-11-10 23:38:19 +00003830 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003831
John McCall2de56d12010-08-25 11:45:40 +00003832 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003833
John McCallf2370c92010-01-06 05:24:50 +00003834 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003835 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003836 return OutputTypeRange;
3837
3838 IntRange SubRange
3839 = GetExprRange(C, CE->getSubExpr(),
3840 std::min(MaxWidth, OutputTypeRange.Width));
3841
3842 // Bail out if the subexpr's range is as wide as the cast type.
3843 if (SubRange.Width >= OutputTypeRange.Width)
3844 return OutputTypeRange;
3845
3846 // Otherwise, we take the smaller width, and we're non-negative if
3847 // either the output type or the subexpr is.
3848 return IntRange(SubRange.Width,
3849 SubRange.NonNegative || OutputTypeRange.NonNegative);
3850 }
3851
3852 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3853 // If we can fold the condition, just take that operand.
3854 bool CondResult;
3855 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3856 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3857 : CO->getFalseExpr(),
3858 MaxWidth);
3859
3860 // Otherwise, conservatively merge.
3861 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3862 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3863 return IntRange::join(L, R);
3864 }
3865
3866 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3867 switch (BO->getOpcode()) {
3868
3869 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003870 case BO_LAnd:
3871 case BO_LOr:
3872 case BO_LT:
3873 case BO_GT:
3874 case BO_LE:
3875 case BO_GE:
3876 case BO_EQ:
3877 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003878 return IntRange::forBoolType();
3879
John McCall862ff872011-07-13 06:35:24 +00003880 // The type of the assignments is the type of the LHS, so the RHS
3881 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003882 case BO_MulAssign:
3883 case BO_DivAssign:
3884 case BO_RemAssign:
3885 case BO_AddAssign:
3886 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003887 case BO_XorAssign:
3888 case BO_OrAssign:
3889 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003890 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003891
John McCall862ff872011-07-13 06:35:24 +00003892 // Simple assignments just pass through the RHS, which will have
3893 // been coerced to the LHS type.
3894 case BO_Assign:
3895 // TODO: bitfields?
3896 return GetExprRange(C, BO->getRHS(), MaxWidth);
3897
John McCallf2370c92010-01-06 05:24:50 +00003898 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003899 case BO_PtrMemD:
3900 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003901 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003902
John McCall60fad452010-01-06 22:07:33 +00003903 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003904 case BO_And:
3905 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003906 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3907 GetExprRange(C, BO->getRHS(), MaxWidth));
3908
John McCallf2370c92010-01-06 05:24:50 +00003909 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003910 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003911 // ...except that we want to treat '1 << (blah)' as logically
3912 // positive. It's an important idiom.
3913 if (IntegerLiteral *I
3914 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3915 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003916 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003917 return IntRange(R.Width, /*NonNegative*/ true);
3918 }
3919 }
3920 // fallthrough
3921
John McCall2de56d12010-08-25 11:45:40 +00003922 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003923 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003924
John McCall60fad452010-01-06 22:07:33 +00003925 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003926 case BO_Shr:
3927 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003928 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3929
3930 // If the shift amount is a positive constant, drop the width by
3931 // that much.
3932 llvm::APSInt shift;
3933 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3934 shift.isNonNegative()) {
3935 unsigned zext = shift.getZExtValue();
3936 if (zext >= L.Width)
3937 L.Width = (L.NonNegative ? 0 : 1);
3938 else
3939 L.Width -= zext;
3940 }
3941
3942 return L;
3943 }
3944
3945 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003946 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003947 return GetExprRange(C, BO->getRHS(), MaxWidth);
3948
John McCall60fad452010-01-06 22:07:33 +00003949 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003950 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003951 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003952 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003953 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003954
John McCall00fe7612011-07-14 22:39:48 +00003955 // The width of a division result is mostly determined by the size
3956 // of the LHS.
3957 case BO_Div: {
3958 // Don't 'pre-truncate' the operands.
3959 unsigned opWidth = C.getIntWidth(E->getType());
3960 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3961
3962 // If the divisor is constant, use that.
3963 llvm::APSInt divisor;
3964 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3965 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3966 if (log2 >= L.Width)
3967 L.Width = (L.NonNegative ? 0 : 1);
3968 else
3969 L.Width = std::min(L.Width - log2, MaxWidth);
3970 return L;
3971 }
3972
3973 // Otherwise, just use the LHS's width.
3974 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3975 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3976 }
3977
3978 // The result of a remainder can't be larger than the result of
3979 // either side.
3980 case BO_Rem: {
3981 // Don't 'pre-truncate' the operands.
3982 unsigned opWidth = C.getIntWidth(E->getType());
3983 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3984 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3985
3986 IntRange meet = IntRange::meet(L, R);
3987 meet.Width = std::min(meet.Width, MaxWidth);
3988 return meet;
3989 }
3990
3991 // The default behavior is okay for these.
3992 case BO_Mul:
3993 case BO_Add:
3994 case BO_Xor:
3995 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003996 break;
3997 }
3998
John McCall00fe7612011-07-14 22:39:48 +00003999 // The default case is to treat the operation as if it were closed
4000 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004001 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4002 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4003 return IntRange::join(L, R);
4004 }
4005
4006 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4007 switch (UO->getOpcode()) {
4008 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004009 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004010 return IntRange::forBoolType();
4011
4012 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004013 case UO_Deref:
4014 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004015 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004016
4017 default:
4018 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4019 }
4020 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004021
4022 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004023 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004024 }
John McCallf2370c92010-01-06 05:24:50 +00004025
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004026 if (FieldDecl *BitField = E->getBitField())
4027 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004028 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004029
John McCall1844a6e2010-11-10 23:38:19 +00004030 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004031}
John McCall51313c32010-01-04 23:31:57 +00004032
Ted Kremenek0692a192012-01-31 05:37:37 +00004033static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004034 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4035}
4036
John McCall51313c32010-01-04 23:31:57 +00004037/// Checks whether the given value, which currently has the given
4038/// source semantics, has the same value when coerced through the
4039/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004040static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4041 const llvm::fltSemantics &Src,
4042 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004043 llvm::APFloat truncated = value;
4044
4045 bool ignored;
4046 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4047 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4048
4049 return truncated.bitwiseIsEqual(value);
4050}
4051
4052/// Checks whether the given value, which currently has the given
4053/// source semantics, has the same value when coerced through the
4054/// target semantics.
4055///
4056/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004057static bool IsSameFloatAfterCast(const APValue &value,
4058 const llvm::fltSemantics &Src,
4059 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004060 if (value.isFloat())
4061 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4062
4063 if (value.isVector()) {
4064 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4065 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4066 return false;
4067 return true;
4068 }
4069
4070 assert(value.isComplexFloat());
4071 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4072 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4073}
4074
Ted Kremenek0692a192012-01-31 05:37:37 +00004075static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004076
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004077static bool IsZero(Sema &S, Expr *E) {
4078 // Suppress cases where we are comparing against an enum constant.
4079 if (const DeclRefExpr *DR =
4080 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4081 if (isa<EnumConstantDecl>(DR->getDecl()))
4082 return false;
4083
4084 // Suppress cases where the '0' value is expanded from a macro.
4085 if (E->getLocStart().isMacroID())
4086 return false;
4087
John McCall323ed742010-05-06 08:58:33 +00004088 llvm::APSInt Value;
4089 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4090}
4091
John McCall372e1032010-10-06 00:25:24 +00004092static bool HasEnumType(Expr *E) {
4093 // Strip off implicit integral promotions.
4094 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004095 if (ICE->getCastKind() != CK_IntegralCast &&
4096 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004097 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004098 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004099 }
4100
4101 return E->getType()->isEnumeralType();
4102}
4103
Ted Kremenek0692a192012-01-31 05:37:37 +00004104static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004105 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004106 if (E->isValueDependent())
4107 return;
4108
John McCall2de56d12010-08-25 11:45:40 +00004109 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004110 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004111 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004112 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004113 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004114 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004115 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004116 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004117 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004118 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004119 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004120 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004121 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004122 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004123 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004124 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4125 }
4126}
4127
4128/// Analyze the operands of the given comparison. Implements the
4129/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004130static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004131 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4132 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004133}
John McCall51313c32010-01-04 23:31:57 +00004134
John McCallba26e582010-01-04 23:21:16 +00004135/// \brief Implements -Wsign-compare.
4136///
Richard Trieudd225092011-09-15 21:56:47 +00004137/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004138static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004139 // The type the comparison is being performed in.
4140 QualType T = E->getLHS()->getType();
4141 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4142 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004143
John McCall323ed742010-05-06 08:58:33 +00004144 // We don't do anything special if this isn't an unsigned integral
4145 // comparison: we're only interested in integral comparisons, and
4146 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004147 //
4148 // We also don't care about value-dependent expressions or expressions
4149 // whose result is a constant.
4150 if (!T->hasUnsignedIntegerRepresentation()
4151 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004152 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004153
Richard Trieudd225092011-09-15 21:56:47 +00004154 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4155 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004156
John McCall323ed742010-05-06 08:58:33 +00004157 // Check to see if one of the (unmodified) operands is of different
4158 // signedness.
4159 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004160 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4161 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004162 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004163 signedOperand = LHS;
4164 unsignedOperand = RHS;
4165 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4166 signedOperand = RHS;
4167 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004168 } else {
John McCall323ed742010-05-06 08:58:33 +00004169 CheckTrivialUnsignedComparison(S, E);
4170 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004171 }
4172
John McCall323ed742010-05-06 08:58:33 +00004173 // Otherwise, calculate the effective range of the signed operand.
4174 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004175
John McCall323ed742010-05-06 08:58:33 +00004176 // Go ahead and analyze implicit conversions in the operands. Note
4177 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004178 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4179 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004180
John McCall323ed742010-05-06 08:58:33 +00004181 // If the signed range is non-negative, -Wsign-compare won't fire,
4182 // but we should still check for comparisons which are always true
4183 // or false.
4184 if (signedRange.NonNegative)
4185 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004186
4187 // For (in)equality comparisons, if the unsigned operand is a
4188 // constant which cannot collide with a overflowed signed operand,
4189 // then reinterpreting the signed operand as unsigned will not
4190 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004191 if (E->isEqualityOp()) {
4192 unsigned comparisonWidth = S.Context.getIntWidth(T);
4193 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004194
John McCall323ed742010-05-06 08:58:33 +00004195 // We should never be unable to prove that the unsigned operand is
4196 // non-negative.
4197 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4198
4199 if (unsignedRange.Width < comparisonWidth)
4200 return;
4201 }
4202
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004203 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4204 S.PDiag(diag::warn_mixed_sign_comparison)
4205 << LHS->getType() << RHS->getType()
4206 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004207}
4208
John McCall15d7d122010-11-11 03:21:53 +00004209/// Analyzes an attempt to assign the given value to a bitfield.
4210///
4211/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004212static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4213 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004214 assert(Bitfield->isBitField());
4215 if (Bitfield->isInvalidDecl())
4216 return false;
4217
John McCall91b60142010-11-11 05:33:51 +00004218 // White-list bool bitfields.
4219 if (Bitfield->getType()->isBooleanType())
4220 return false;
4221
Douglas Gregor46ff3032011-02-04 13:09:01 +00004222 // Ignore value- or type-dependent expressions.
4223 if (Bitfield->getBitWidth()->isValueDependent() ||
4224 Bitfield->getBitWidth()->isTypeDependent() ||
4225 Init->isValueDependent() ||
4226 Init->isTypeDependent())
4227 return false;
4228
John McCall15d7d122010-11-11 03:21:53 +00004229 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4230
Richard Smith80d4b552011-12-28 19:48:30 +00004231 llvm::APSInt Value;
4232 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004233 return false;
4234
John McCall15d7d122010-11-11 03:21:53 +00004235 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004236 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004237
4238 if (OriginalWidth <= FieldWidth)
4239 return false;
4240
Eli Friedman3a643af2012-01-26 23:11:39 +00004241 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004242 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004243 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004244
Eli Friedman3a643af2012-01-26 23:11:39 +00004245 // Check whether the stored value is equal to the original value.
4246 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004247 if (Value == TruncatedValue)
4248 return false;
4249
Eli Friedman3a643af2012-01-26 23:11:39 +00004250 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004251 // therefore don't strictly fit into a signed bitfield of width 1.
4252 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004253 return false;
4254
John McCall15d7d122010-11-11 03:21:53 +00004255 std::string PrettyValue = Value.toString(10);
4256 std::string PrettyTrunc = TruncatedValue.toString(10);
4257
4258 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4259 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4260 << Init->getSourceRange();
4261
4262 return true;
4263}
4264
John McCallbeb22aa2010-11-09 23:24:47 +00004265/// Analyze the given simple or compound assignment for warning-worthy
4266/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004267static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004268 // Just recurse on the LHS.
4269 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4270
4271 // We want to recurse on the RHS as normal unless we're assigning to
4272 // a bitfield.
4273 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004274 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4275 E->getOperatorLoc())) {
4276 // Recurse, ignoring any implicit conversions on the RHS.
4277 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4278 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004279 }
4280 }
4281
4282 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4283}
4284
John McCall51313c32010-01-04 23:31:57 +00004285/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004286static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004287 SourceLocation CContext, unsigned diag,
4288 bool pruneControlFlow = false) {
4289 if (pruneControlFlow) {
4290 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4291 S.PDiag(diag)
4292 << SourceType << T << E->getSourceRange()
4293 << SourceRange(CContext));
4294 return;
4295 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004296 S.Diag(E->getExprLoc(), diag)
4297 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4298}
4299
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004300/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004301static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004302 SourceLocation CContext, unsigned diag,
4303 bool pruneControlFlow = false) {
4304 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004305}
4306
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004307/// Diagnose an implicit cast from a literal expression. Does not warn when the
4308/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004309void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4310 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004311 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004312 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004313 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004314 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4315 T->hasUnsignedIntegerRepresentation());
4316 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004317 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004318 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004319 return;
4320
David Blaikiebe0ee872012-05-15 16:56:36 +00004321 SmallString<16> PrettySourceValue;
4322 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004323 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004324 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4325 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4326 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004327 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004328
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004329 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004330 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4331 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004332}
4333
John McCall091f23f2010-11-09 22:22:12 +00004334std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4335 if (!Range.Width) return "0";
4336
4337 llvm::APSInt ValueInRange = Value;
4338 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004339 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004340 return ValueInRange.toString(10);
4341}
4342
John McCall323ed742010-05-06 08:58:33 +00004343void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004344 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004345 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004346
John McCall323ed742010-05-06 08:58:33 +00004347 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4348 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4349 if (Source == Target) return;
4350 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004351
Chandler Carruth108f7562011-07-26 05:40:03 +00004352 // If the conversion context location is invalid don't complain. We also
4353 // don't want to emit a warning if the issue occurs from the expansion of
4354 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4355 // delay this check as long as possible. Once we detect we are in that
4356 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004357 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004358 return;
4359
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004360 // Diagnose implicit casts to bool.
4361 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4362 if (isa<StringLiteral>(E))
4363 // Warn on string literal to bool. Checks for string literals in logical
4364 // expressions, for instances, assert(0 && "error here"), is prevented
4365 // by a check in AnalyzeImplicitConversions().
4366 return DiagnoseImpCast(S, E, T, CC,
4367 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004368 if (Source->isFunctionType()) {
4369 // Warn on function to bool. Checks free functions and static member
4370 // functions. Weakly imported functions are excluded from the check,
4371 // since it's common to test their value to check whether the linker
4372 // found a definition for them.
4373 ValueDecl *D = 0;
4374 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4375 D = R->getDecl();
4376 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4377 D = M->getMemberDecl();
4378 }
4379
4380 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004381 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4382 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4383 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004384 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4385 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4386 QualType ReturnType;
4387 UnresolvedSet<4> NonTemplateOverloads;
4388 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4389 if (!ReturnType.isNull()
4390 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4391 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4392 << FixItHint::CreateInsertion(
4393 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004394 return;
4395 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004396 }
4397 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004398 }
John McCall51313c32010-01-04 23:31:57 +00004399
4400 // Strip vector types.
4401 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004402 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004403 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004404 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004405 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004406 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004407
4408 // If the vector cast is cast between two vectors of the same size, it is
4409 // a bitcast, not a conversion.
4410 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4411 return;
John McCall51313c32010-01-04 23:31:57 +00004412
4413 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4414 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4415 }
4416
4417 // Strip complex types.
4418 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004419 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004420 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004421 return;
4422
John McCallb4eb64d2010-10-08 02:01:28 +00004423 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004424 }
John McCall51313c32010-01-04 23:31:57 +00004425
4426 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4427 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4428 }
4429
4430 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4431 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4432
4433 // If the source is floating point...
4434 if (SourceBT && SourceBT->isFloatingPoint()) {
4435 // ...and the target is floating point...
4436 if (TargetBT && TargetBT->isFloatingPoint()) {
4437 // ...then warn if we're dropping FP rank.
4438
4439 // Builtin FP kinds are ordered by increasing FP rank.
4440 if (SourceBT->getKind() > TargetBT->getKind()) {
4441 // Don't warn about float constants that are precisely
4442 // representable in the target type.
4443 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004444 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004445 // Value might be a float, a float vector, or a float complex.
4446 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004447 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4448 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004449 return;
4450 }
4451
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004452 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004453 return;
4454
John McCallb4eb64d2010-10-08 02:01:28 +00004455 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004456 }
4457 return;
4458 }
4459
Ted Kremenekef9ff882011-03-10 20:03:42 +00004460 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004461 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004462 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004463 return;
4464
Chandler Carrutha5b93322011-02-17 11:05:49 +00004465 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004466 // We also want to warn on, e.g., "int i = -1.234"
4467 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4468 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4469 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4470
Chandler Carruthf65076e2011-04-10 08:36:24 +00004471 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4472 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004473 } else {
4474 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4475 }
4476 }
John McCall51313c32010-01-04 23:31:57 +00004477
4478 return;
4479 }
4480
Richard Trieu1838ca52011-05-29 19:59:02 +00004481 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004482 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004483 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004484 SourceLocation Loc = E->getSourceRange().getBegin();
4485 if (Loc.isMacroID())
4486 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004487 if (!Loc.isMacroID() || CC.isMacroID())
4488 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4489 << T << clang::SourceRange(CC)
4490 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004491 }
4492
David Blaikieb26331b2012-06-19 21:19:06 +00004493 if (!Source->isIntegerType() || !Target->isIntegerType())
4494 return;
4495
David Blaikiebe0ee872012-05-15 16:56:36 +00004496 // TODO: remove this early return once the false positives for constant->bool
4497 // in templates, macros, etc, are reduced or removed.
4498 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4499 return;
4500
John McCall323ed742010-05-06 08:58:33 +00004501 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004502 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004503
4504 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004505 // If the source is a constant, use a default-on diagnostic.
4506 // TODO: this should happen for bitfield stores, too.
4507 llvm::APSInt Value(32);
4508 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004509 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004510 return;
4511
John McCall091f23f2010-11-09 22:22:12 +00004512 std::string PrettySourceValue = Value.toString(10);
4513 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4514
Ted Kremenek5e745da2011-10-22 02:37:33 +00004515 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4516 S.PDiag(diag::warn_impcast_integer_precision_constant)
4517 << PrettySourceValue << PrettyTargetValue
4518 << E->getType() << T << E->getSourceRange()
4519 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004520 return;
4521 }
4522
Chris Lattnerb792b302011-06-14 04:51:15 +00004523 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004524 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004525 return;
4526
David Blaikie37050842012-04-12 22:40:54 +00004527 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004528 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4529 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004530 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004531 }
4532
4533 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4534 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4535 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004536
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004537 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004538 return;
4539
John McCall323ed742010-05-06 08:58:33 +00004540 unsigned DiagID = diag::warn_impcast_integer_sign;
4541
4542 // Traditionally, gcc has warned about this under -Wsign-compare.
4543 // We also want to warn about it in -Wconversion.
4544 // So if -Wconversion is off, use a completely identical diagnostic
4545 // in the sign-compare group.
4546 // The conditional-checking code will
4547 if (ICContext) {
4548 DiagID = diag::warn_impcast_integer_sign_conditional;
4549 *ICContext = true;
4550 }
4551
John McCallb4eb64d2010-10-08 02:01:28 +00004552 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004553 }
4554
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004555 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004556 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4557 // type, to give us better diagnostics.
4558 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004559 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004560 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4561 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4562 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4563 SourceType = S.Context.getTypeDeclType(Enum);
4564 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4565 }
4566 }
4567
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004568 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4569 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4570 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004571 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004572 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004573 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004574 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004575 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004576 return;
4577
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004578 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004579 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004580 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004581
John McCall51313c32010-01-04 23:31:57 +00004582 return;
4583}
4584
David Blaikie9fb1ac52012-05-15 21:57:38 +00004585void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4586 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004587
4588void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004589 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004590 E = E->IgnoreParenImpCasts();
4591
4592 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004593 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004594
John McCallb4eb64d2010-10-08 02:01:28 +00004595 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004596 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004597 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004598 return;
4599}
4600
David Blaikie9fb1ac52012-05-15 21:57:38 +00004601void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4602 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004603 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004604
4605 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004606 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4607 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004608
4609 // If -Wconversion would have warned about either of the candidates
4610 // for a signedness conversion to the context type...
4611 if (!Suspicious) return;
4612
4613 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004614 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4615 CC))
John McCall323ed742010-05-06 08:58:33 +00004616 return;
4617
John McCall323ed742010-05-06 08:58:33 +00004618 // ...then check whether it would have warned about either of the
4619 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004620 if (E->getType() == T) return;
4621
4622 Suspicious = false;
4623 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4624 E->getType(), CC, &Suspicious);
4625 if (!Suspicious)
4626 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004627 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004628}
4629
4630/// AnalyzeImplicitConversions - Find and report any interesting
4631/// implicit conversions in the given expression. There are a couple
4632/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004633void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004634 QualType T = OrigE->getType();
4635 Expr *E = OrigE->IgnoreParenImpCasts();
4636
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004637 if (E->isTypeDependent() || E->isValueDependent())
4638 return;
4639
John McCall323ed742010-05-06 08:58:33 +00004640 // For conditional operators, we analyze the arguments as if they
4641 // were being fed directly into the output.
4642 if (isa<ConditionalOperator>(E)) {
4643 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004644 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004645 return;
4646 }
4647
4648 // Go ahead and check any implicit conversions we might have skipped.
4649 // The non-canonical typecheck is just an optimization;
4650 // CheckImplicitConversion will filter out dead implicit conversions.
4651 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004652 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004653
4654 // Now continue drilling into this expression.
4655
4656 // Skip past explicit casts.
4657 if (isa<ExplicitCastExpr>(E)) {
4658 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004659 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004660 }
4661
John McCallbeb22aa2010-11-09 23:24:47 +00004662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4663 // Do a somewhat different check with comparison operators.
4664 if (BO->isComparisonOp())
4665 return AnalyzeComparison(S, BO);
4666
Eli Friedman0fa06382012-01-26 23:34:06 +00004667 // And with simple assignments.
4668 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004669 return AnalyzeAssignment(S, BO);
4670 }
John McCall323ed742010-05-06 08:58:33 +00004671
4672 // These break the otherwise-useful invariant below. Fortunately,
4673 // we don't really need to recurse into them, because any internal
4674 // expressions should have been analyzed already when they were
4675 // built into statements.
4676 if (isa<StmtExpr>(E)) return;
4677
4678 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004679 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004680
4681 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004682 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004683 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4684 bool IsLogicalOperator = BO && BO->isLogicalOp();
4685 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004686 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004687 if (!ChildExpr)
4688 continue;
4689
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004690 if (IsLogicalOperator &&
4691 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4692 // Ignore checking string literals that are in logical operators.
4693 continue;
4694 AnalyzeImplicitConversions(S, ChildExpr, CC);
4695 }
John McCall323ed742010-05-06 08:58:33 +00004696}
4697
4698} // end anonymous namespace
4699
4700/// Diagnoses "dangerous" implicit conversions within the given
4701/// expression (which is a full expression). Implements -Wconversion
4702/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004703///
4704/// \param CC the "context" location of the implicit conversion, i.e.
4705/// the most location of the syntactic entity requiring the implicit
4706/// conversion
4707void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004708 // Don't diagnose in unevaluated contexts.
4709 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4710 return;
4711
4712 // Don't diagnose for value- or type-dependent expressions.
4713 if (E->isTypeDependent() || E->isValueDependent())
4714 return;
4715
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004716 // Check for array bounds violations in cases where the check isn't triggered
4717 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4718 // ArraySubscriptExpr is on the RHS of a variable initialization.
4719 CheckArrayAccess(E);
4720
John McCallb4eb64d2010-10-08 02:01:28 +00004721 // This is not the right CC for (e.g.) a variable initialization.
4722 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004723}
4724
John McCall15d7d122010-11-11 03:21:53 +00004725void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4726 FieldDecl *BitField,
4727 Expr *Init) {
4728 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4729}
4730
Mike Stumpf8c49212010-01-21 03:59:47 +00004731/// CheckParmsForFunctionDef - Check that the parameters of the given
4732/// function are appropriate for the definition of a function. This
4733/// takes care of any checks that cannot be performed on the
4734/// declaration itself, e.g., that the types of each of the function
4735/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004736bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4737 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004738 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004739 for (; P != PEnd; ++P) {
4740 ParmVarDecl *Param = *P;
4741
Mike Stumpf8c49212010-01-21 03:59:47 +00004742 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4743 // function declarator that is part of a function definition of
4744 // that function shall not have incomplete type.
4745 //
4746 // This is also C++ [dcl.fct]p6.
4747 if (!Param->isInvalidDecl() &&
4748 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004749 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004750 Param->setInvalidDecl();
4751 HasInvalidParm = true;
4752 }
4753
4754 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4755 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004756 if (CheckParameterNames &&
4757 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004758 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004759 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004760 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004761
4762 // C99 6.7.5.3p12:
4763 // If the function declarator is not part of a definition of that
4764 // function, parameters may have incomplete type and may use the [*]
4765 // notation in their sequences of declarator specifiers to specify
4766 // variable length array types.
4767 QualType PType = Param->getOriginalType();
4768 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4769 if (AT->getSizeModifier() == ArrayType::Star) {
4770 // FIXME: This diagnosic should point the the '[*]' if source-location
4771 // information is added for it.
4772 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4773 }
4774 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004775 }
4776
4777 return HasInvalidParm;
4778}
John McCallb7f4ffe2010-08-12 21:44:57 +00004779
4780/// CheckCastAlign - Implements -Wcast-align, which warns when a
4781/// pointer cast increases the alignment requirements.
4782void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4783 // This is actually a lot of work to potentially be doing on every
4784 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004785 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4786 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004787 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004788 return;
4789
4790 // Ignore dependent types.
4791 if (T->isDependentType() || Op->getType()->isDependentType())
4792 return;
4793
4794 // Require that the destination be a pointer type.
4795 const PointerType *DestPtr = T->getAs<PointerType>();
4796 if (!DestPtr) return;
4797
4798 // If the destination has alignment 1, we're done.
4799 QualType DestPointee = DestPtr->getPointeeType();
4800 if (DestPointee->isIncompleteType()) return;
4801 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4802 if (DestAlign.isOne()) return;
4803
4804 // Require that the source be a pointer type.
4805 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4806 if (!SrcPtr) return;
4807 QualType SrcPointee = SrcPtr->getPointeeType();
4808
4809 // Whitelist casts from cv void*. We already implicitly
4810 // whitelisted casts to cv void*, since they have alignment 1.
4811 // Also whitelist casts involving incomplete types, which implicitly
4812 // includes 'void'.
4813 if (SrcPointee->isIncompleteType()) return;
4814
4815 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4816 if (SrcAlign >= DestAlign) return;
4817
4818 Diag(TRange.getBegin(), diag::warn_cast_align)
4819 << Op->getType() << T
4820 << static_cast<unsigned>(SrcAlign.getQuantity())
4821 << static_cast<unsigned>(DestAlign.getQuantity())
4822 << TRange << Op->getSourceRange();
4823}
4824
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004825static const Type* getElementType(const Expr *BaseExpr) {
4826 const Type* EltType = BaseExpr->getType().getTypePtr();
4827 if (EltType->isAnyPointerType())
4828 return EltType->getPointeeType().getTypePtr();
4829 else if (EltType->isArrayType())
4830 return EltType->getBaseElementTypeUnsafe();
4831 return EltType;
4832}
4833
Chandler Carruthc2684342011-08-05 09:10:50 +00004834/// \brief Check whether this array fits the idiom of a size-one tail padded
4835/// array member of a struct.
4836///
4837/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4838/// commonly used to emulate flexible arrays in C89 code.
4839static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4840 const NamedDecl *ND) {
4841 if (Size != 1 || !ND) return false;
4842
4843 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4844 if (!FD) return false;
4845
4846 // Don't consider sizes resulting from macro expansions or template argument
4847 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004848
4849 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004850 while (TInfo) {
4851 TypeLoc TL = TInfo->getTypeLoc();
4852 // Look through typedefs.
4853 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4854 if (TTL) {
4855 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4856 TInfo = TDL->getTypeSourceInfo();
4857 continue;
4858 }
4859 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4860 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004861 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4862 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004863 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004864 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004865
4866 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004867 if (!RD) return false;
4868 if (RD->isUnion()) return false;
4869 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4870 if (!CRD->isStandardLayout()) return false;
4871 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004872
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004873 // See if this is the last field decl in the record.
4874 const Decl *D = FD;
4875 while ((D = D->getNextDeclInContext()))
4876 if (isa<FieldDecl>(D))
4877 return false;
4878 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004879}
4880
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004881void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004882 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004883 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004884 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004885 if (IndexExpr->isValueDependent())
4886 return;
4887
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004888 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004889 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004890 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004891 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004892 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004893 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004894
Chandler Carruth34064582011-02-17 20:55:08 +00004895 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004896 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004897 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004898 if (IndexNegated)
4899 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004900
Chandler Carruthba447122011-08-05 08:07:29 +00004901 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004902 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4903 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004904 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004905 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004906
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004907 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004908 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004909 if (!size.isStrictlyPositive())
4910 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004911
4912 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004913 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004914 // Make sure we're comparing apples to apples when comparing index to size
4915 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4916 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004917 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004918 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004919 if (ptrarith_typesize != array_typesize) {
4920 // There's a cast to a different size type involved
4921 uint64_t ratio = array_typesize / ptrarith_typesize;
4922 // TODO: Be smarter about handling cases where array_typesize is not a
4923 // multiple of ptrarith_typesize
4924 if (ptrarith_typesize * ratio == array_typesize)
4925 size *= llvm::APInt(size.getBitWidth(), ratio);
4926 }
4927 }
4928
Chandler Carruth34064582011-02-17 20:55:08 +00004929 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004930 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004931 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004932 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004933
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004934 // For array subscripting the index must be less than size, but for pointer
4935 // arithmetic also allow the index (offset) to be equal to size since
4936 // computing the next address after the end of the array is legal and
4937 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004938 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004939 return;
4940
4941 // Also don't warn for arrays of size 1 which are members of some
4942 // structure. These are often used to approximate flexible arrays in C89
4943 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004944 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004945 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004946
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004947 // Suppress the warning if the subscript expression (as identified by the
4948 // ']' location) and the index expression are both from macro expansions
4949 // within a system header.
4950 if (ASE) {
4951 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4952 ASE->getRBracketLoc());
4953 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4954 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4955 IndexExpr->getLocStart());
4956 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4957 return;
4958 }
4959 }
4960
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004961 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004962 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004963 DiagID = diag::warn_array_index_exceeds_bounds;
4964
4965 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4966 PDiag(DiagID) << index.toString(10, true)
4967 << size.toString(10, true)
4968 << (unsigned)size.getLimitedValue(~0U)
4969 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004970 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004971 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004972 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004973 DiagID = diag::warn_ptr_arith_precedes_bounds;
4974 if (index.isNegative()) index = -index;
4975 }
4976
4977 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4978 PDiag(DiagID) << index.toString(10, true)
4979 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004980 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004981
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004982 if (!ND) {
4983 // Try harder to find a NamedDecl to point at in the note.
4984 while (const ArraySubscriptExpr *ASE =
4985 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4986 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4987 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4988 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4989 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4990 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4991 }
4992
Chandler Carruth35001ca2011-02-17 21:10:52 +00004993 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004994 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4995 PDiag(diag::note_array_index_out_of_bounds)
4996 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004997}
4998
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004999void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005000 int AllowOnePastEnd = 0;
5001 while (expr) {
5002 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005003 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005004 case Stmt::ArraySubscriptExprClass: {
5005 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005006 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005007 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005008 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005009 }
5010 case Stmt::UnaryOperatorClass: {
5011 // Only unwrap the * and & unary operators
5012 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5013 expr = UO->getSubExpr();
5014 switch (UO->getOpcode()) {
5015 case UO_AddrOf:
5016 AllowOnePastEnd++;
5017 break;
5018 case UO_Deref:
5019 AllowOnePastEnd--;
5020 break;
5021 default:
5022 return;
5023 }
5024 break;
5025 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005026 case Stmt::ConditionalOperatorClass: {
5027 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5028 if (const Expr *lhs = cond->getLHS())
5029 CheckArrayAccess(lhs);
5030 if (const Expr *rhs = cond->getRHS())
5031 CheckArrayAccess(rhs);
5032 return;
5033 }
5034 default:
5035 return;
5036 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005037 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005038}
John McCallf85e1932011-06-15 23:02:42 +00005039
5040//===--- CHECK: Objective-C retain cycles ----------------------------------//
5041
5042namespace {
5043 struct RetainCycleOwner {
5044 RetainCycleOwner() : Variable(0), Indirect(false) {}
5045 VarDecl *Variable;
5046 SourceRange Range;
5047 SourceLocation Loc;
5048 bool Indirect;
5049
5050 void setLocsFrom(Expr *e) {
5051 Loc = e->getExprLoc();
5052 Range = e->getSourceRange();
5053 }
5054 };
5055}
5056
5057/// Consider whether capturing the given variable can possibly lead to
5058/// a retain cycle.
5059static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5060 // In ARC, it's captured strongly iff the variable has __strong
5061 // lifetime. In MRR, it's captured strongly if the variable is
5062 // __block and has an appropriate type.
5063 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5064 return false;
5065
5066 owner.Variable = var;
5067 owner.setLocsFrom(ref);
5068 return true;
5069}
5070
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005071static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005072 while (true) {
5073 e = e->IgnoreParens();
5074 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5075 switch (cast->getCastKind()) {
5076 case CK_BitCast:
5077 case CK_LValueBitCast:
5078 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005079 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005080 e = cast->getSubExpr();
5081 continue;
5082
John McCallf85e1932011-06-15 23:02:42 +00005083 default:
5084 return false;
5085 }
5086 }
5087
5088 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5089 ObjCIvarDecl *ivar = ref->getDecl();
5090 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5091 return false;
5092
5093 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005094 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005095 return false;
5096
5097 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5098 owner.Indirect = true;
5099 return true;
5100 }
5101
5102 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5103 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5104 if (!var) return false;
5105 return considerVariable(var, ref, owner);
5106 }
5107
John McCallf85e1932011-06-15 23:02:42 +00005108 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5109 if (member->isArrow()) return false;
5110
5111 // Don't count this as an indirect ownership.
5112 e = member->getBase();
5113 continue;
5114 }
5115
John McCall4b9c2d22011-11-06 09:01:30 +00005116 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5117 // Only pay attention to pseudo-objects on property references.
5118 ObjCPropertyRefExpr *pre
5119 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5120 ->IgnoreParens());
5121 if (!pre) return false;
5122 if (pre->isImplicitProperty()) return false;
5123 ObjCPropertyDecl *property = pre->getExplicitProperty();
5124 if (!property->isRetaining() &&
5125 !(property->getPropertyIvarDecl() &&
5126 property->getPropertyIvarDecl()->getType()
5127 .getObjCLifetime() == Qualifiers::OCL_Strong))
5128 return false;
5129
5130 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005131 if (pre->isSuperReceiver()) {
5132 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5133 if (!owner.Variable)
5134 return false;
5135 owner.Loc = pre->getLocation();
5136 owner.Range = pre->getSourceRange();
5137 return true;
5138 }
John McCall4b9c2d22011-11-06 09:01:30 +00005139 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5140 ->getSourceExpr());
5141 continue;
5142 }
5143
John McCallf85e1932011-06-15 23:02:42 +00005144 // Array ivars?
5145
5146 return false;
5147 }
5148}
5149
5150namespace {
5151 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5152 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5153 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5154 Variable(variable), Capturer(0) {}
5155
5156 VarDecl *Variable;
5157 Expr *Capturer;
5158
5159 void VisitDeclRefExpr(DeclRefExpr *ref) {
5160 if (ref->getDecl() == Variable && !Capturer)
5161 Capturer = ref;
5162 }
5163
John McCallf85e1932011-06-15 23:02:42 +00005164 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5165 if (Capturer) return;
5166 Visit(ref->getBase());
5167 if (Capturer && ref->isFreeIvar())
5168 Capturer = ref;
5169 }
5170
5171 void VisitBlockExpr(BlockExpr *block) {
5172 // Look inside nested blocks
5173 if (block->getBlockDecl()->capturesVariable(Variable))
5174 Visit(block->getBlockDecl()->getBody());
5175 }
5176 };
5177}
5178
5179/// Check whether the given argument is a block which captures a
5180/// variable.
5181static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5182 assert(owner.Variable && owner.Loc.isValid());
5183
5184 e = e->IgnoreParenCasts();
5185 BlockExpr *block = dyn_cast<BlockExpr>(e);
5186 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5187 return 0;
5188
5189 FindCaptureVisitor visitor(S.Context, owner.Variable);
5190 visitor.Visit(block->getBlockDecl()->getBody());
5191 return visitor.Capturer;
5192}
5193
5194static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5195 RetainCycleOwner &owner) {
5196 assert(capturer);
5197 assert(owner.Variable && owner.Loc.isValid());
5198
5199 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5200 << owner.Variable << capturer->getSourceRange();
5201 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5202 << owner.Indirect << owner.Range;
5203}
5204
5205/// Check for a keyword selector that starts with the word 'add' or
5206/// 'set'.
5207static bool isSetterLikeSelector(Selector sel) {
5208 if (sel.isUnarySelector()) return false;
5209
Chris Lattner5f9e2722011-07-23 10:55:15 +00005210 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005211 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005212 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005213 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005214 else if (str.startswith("add")) {
5215 // Specially whitelist 'addOperationWithBlock:'.
5216 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5217 return false;
5218 str = str.substr(3);
5219 }
John McCallf85e1932011-06-15 23:02:42 +00005220 else
5221 return false;
5222
5223 if (str.empty()) return true;
5224 return !islower(str.front());
5225}
5226
5227/// Check a message send to see if it's likely to cause a retain cycle.
5228void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5229 // Only check instance methods whose selector looks like a setter.
5230 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5231 return;
5232
5233 // Try to find a variable that the receiver is strongly owned by.
5234 RetainCycleOwner owner;
5235 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005236 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005237 return;
5238 } else {
5239 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5240 owner.Variable = getCurMethodDecl()->getSelfDecl();
5241 owner.Loc = msg->getSuperLoc();
5242 owner.Range = msg->getSuperLoc();
5243 }
5244
5245 // Check whether the receiver is captured by any of the arguments.
5246 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5247 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5248 return diagnoseRetainCycle(*this, capturer, owner);
5249}
5250
5251/// Check a property assign to see if it's likely to cause a retain cycle.
5252void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5253 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005254 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005255 return;
5256
5257 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5258 diagnoseRetainCycle(*this, capturer, owner);
5259}
5260
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005261bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005262 QualType LHS, Expr *RHS) {
5263 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5264 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005265 return false;
5266 // strip off any implicit cast added to get to the one arc-specific
5267 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005268 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005269 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005270 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005271 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005272 return true;
5273 }
5274 RHS = cast->getSubExpr();
5275 }
5276 return false;
John McCallf85e1932011-06-15 23:02:42 +00005277}
5278
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005279void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5280 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005281 QualType LHSType;
5282 // PropertyRef on LHS type need be directly obtained from
5283 // its declaration as it has a PsuedoType.
5284 ObjCPropertyRefExpr *PRE
5285 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5286 if (PRE && !PRE->isImplicitProperty()) {
5287 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5288 if (PD)
5289 LHSType = PD->getType();
5290 }
5291
5292 if (LHSType.isNull())
5293 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005294 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5295 return;
5296 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5297 // FIXME. Check for other life times.
5298 if (LT != Qualifiers::OCL_None)
5299 return;
5300
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005301 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005302 if (PRE->isImplicitProperty())
5303 return;
5304 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5305 if (!PD)
5306 return;
5307
5308 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005309 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5310 // when 'assign' attribute was not explicitly specified
5311 // by user, ignore it and rely on property type itself
5312 // for lifetime info.
5313 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5314 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5315 LHSType->isObjCRetainableType())
5316 return;
5317
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005318 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005319 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005320 Diag(Loc, diag::warn_arc_retained_property_assign)
5321 << RHS->getSourceRange();
5322 return;
5323 }
5324 RHS = cast->getSubExpr();
5325 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005326 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005327 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5328 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5329 if (cast->getCastKind() == CK_ARCConsumeObject) {
5330 Diag(Loc, diag::warn_arc_retained_assign)
5331 << 0 << 0<< RHS->getSourceRange();
5332 return;
5333 }
5334 RHS = cast->getSubExpr();
5335 }
5336 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005337 }
5338}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005339
5340//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5341
5342namespace {
5343bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5344 SourceLocation StmtLoc,
5345 const NullStmt *Body) {
5346 // Do not warn if the body is a macro that expands to nothing, e.g:
5347 //
5348 // #define CALL(x)
5349 // if (condition)
5350 // CALL(0);
5351 //
5352 if (Body->hasLeadingEmptyMacro())
5353 return false;
5354
5355 // Get line numbers of statement and body.
5356 bool StmtLineInvalid;
5357 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5358 &StmtLineInvalid);
5359 if (StmtLineInvalid)
5360 return false;
5361
5362 bool BodyLineInvalid;
5363 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5364 &BodyLineInvalid);
5365 if (BodyLineInvalid)
5366 return false;
5367
5368 // Warn if null statement and body are on the same line.
5369 if (StmtLine != BodyLine)
5370 return false;
5371
5372 return true;
5373}
5374} // Unnamed namespace
5375
5376void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5377 const Stmt *Body,
5378 unsigned DiagID) {
5379 // Since this is a syntactic check, don't emit diagnostic for template
5380 // instantiations, this just adds noise.
5381 if (CurrentInstantiationScope)
5382 return;
5383
5384 // The body should be a null statement.
5385 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5386 if (!NBody)
5387 return;
5388
5389 // Do the usual checks.
5390 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5391 return;
5392
5393 Diag(NBody->getSemiLoc(), DiagID);
5394 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5395}
5396
5397void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5398 const Stmt *PossibleBody) {
5399 assert(!CurrentInstantiationScope); // Ensured by caller
5400
5401 SourceLocation StmtLoc;
5402 const Stmt *Body;
5403 unsigned DiagID;
5404 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5405 StmtLoc = FS->getRParenLoc();
5406 Body = FS->getBody();
5407 DiagID = diag::warn_empty_for_body;
5408 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5409 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5410 Body = WS->getBody();
5411 DiagID = diag::warn_empty_while_body;
5412 } else
5413 return; // Neither `for' nor `while'.
5414
5415 // The body should be a null statement.
5416 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5417 if (!NBody)
5418 return;
5419
5420 // Skip expensive checks if diagnostic is disabled.
5421 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5422 DiagnosticsEngine::Ignored)
5423 return;
5424
5425 // Do the usual checks.
5426 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5427 return;
5428
5429 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5430 // noise level low, emit diagnostics only if for/while is followed by a
5431 // CompoundStmt, e.g.:
5432 // for (int i = 0; i < n; i++);
5433 // {
5434 // a(i);
5435 // }
5436 // or if for/while is followed by a statement with more indentation
5437 // than for/while itself:
5438 // for (int i = 0; i < n; i++);
5439 // a(i);
5440 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5441 if (!ProbableTypo) {
5442 bool BodyColInvalid;
5443 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5444 PossibleBody->getLocStart(),
5445 &BodyColInvalid);
5446 if (BodyColInvalid)
5447 return;
5448
5449 bool StmtColInvalid;
5450 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5451 S->getLocStart(),
5452 &StmtColInvalid);
5453 if (StmtColInvalid)
5454 return;
5455
5456 if (BodyCol > StmtCol)
5457 ProbableTypo = true;
5458 }
5459
5460 if (ProbableTypo) {
5461 Diag(NBody->getSemiLoc(), DiagID);
5462 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5463 }
5464}