blob: eddb612fc6eab98cd89afdf0875e3e34ce6eb51c [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000035#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000036#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000037#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000038#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000039#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000046 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000047}
48
John McCall8e10f3b2011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerougee5939212012-04-28 17:39:16 +000069/// Check that the first argument to __builtin_annotation is an integer
70/// and the second argument is a non-wide string literal.
71static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
72 if (checkArgCount(S, TheCall, 2))
73 return true;
74
75 // First argument should be an integer.
76 Expr *ValArg = TheCall->getArg(0);
77 QualType Ty = ValArg->getType();
78 if (!Ty->isIntegerType()) {
79 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
80 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000081 return true;
82 }
Julien Lerougee5939212012-04-28 17:39:16 +000083
84 // Second argument should be a constant string.
85 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
86 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
87 if (!Literal || !Literal->isAscii()) {
88 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
89 << StrArg->getSourceRange();
90 return true;
91 }
92
93 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000094 return false;
95}
96
John McCall60d7b3a2010-08-24 06:29:42 +000097ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000098Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000099 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000100
Chris Lattner946928f2010-10-01 23:23:24 +0000101 // Find out if any arguments are required to be integer constant expressions.
102 unsigned ICEArguments = 0;
103 ASTContext::GetBuiltinTypeError Error;
104 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
105 if (Error != ASTContext::GE_None)
106 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
107
108 // If any arguments are required to be ICE's, check and diagnose.
109 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
110 // Skip arguments not required to be ICE's.
111 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
112
113 llvm::APSInt Result;
114 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
115 return true;
116 ICEArguments &= ~(1 << ArgNo);
117 }
118
Anders Carlssond406bf02009-08-16 01:56:34 +0000119 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000120 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000121 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000122 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000123 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000125 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000126 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000127 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 if (SemaBuiltinVAStart(TheCall))
129 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000130 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000131 case Builtin::BI__builtin_isgreater:
132 case Builtin::BI__builtin_isgreaterequal:
133 case Builtin::BI__builtin_isless:
134 case Builtin::BI__builtin_islessequal:
135 case Builtin::BI__builtin_islessgreater:
136 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 if (SemaBuiltinUnorderedCompare(TheCall))
138 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000139 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000140 case Builtin::BI__builtin_fpclassify:
141 if (SemaBuiltinFPClassification(TheCall, 6))
142 return ExprError();
143 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000144 case Builtin::BI__builtin_isfinite:
145 case Builtin::BI__builtin_isinf:
146 case Builtin::BI__builtin_isinf_sign:
147 case Builtin::BI__builtin_isnan:
148 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000149 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000150 return ExprError();
151 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000152 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 return SemaBuiltinShuffleVector(TheCall);
154 // TheCall will be freed by the smart pointer here, but that's fine, since
155 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000156 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000157 if (SemaBuiltinPrefetch(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000160 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 if (SemaBuiltinObjectSize(TheCall))
162 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000163 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000164 case Builtin::BI__builtin_longjmp:
165 if (SemaBuiltinLongjmp(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000168
169 case Builtin::BI__builtin_classify_type:
170 if (checkArgCount(*this, TheCall, 1)) return true;
171 TheCall->setType(Context.IntTy);
172 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000173 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000174 if (checkArgCount(*this, TheCall, 1)) return true;
175 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000176 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000177 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000178 case Builtin::BI__sync_fetch_and_add_1:
179 case Builtin::BI__sync_fetch_and_add_2:
180 case Builtin::BI__sync_fetch_and_add_4:
181 case Builtin::BI__sync_fetch_and_add_8:
182 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000183 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000184 case Builtin::BI__sync_fetch_and_sub_1:
185 case Builtin::BI__sync_fetch_and_sub_2:
186 case Builtin::BI__sync_fetch_and_sub_4:
187 case Builtin::BI__sync_fetch_and_sub_8:
188 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000190 case Builtin::BI__sync_fetch_and_or_1:
191 case Builtin::BI__sync_fetch_and_or_2:
192 case Builtin::BI__sync_fetch_and_or_4:
193 case Builtin::BI__sync_fetch_and_or_8:
194 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_and_1:
197 case Builtin::BI__sync_fetch_and_and_2:
198 case Builtin::BI__sync_fetch_and_and_4:
199 case Builtin::BI__sync_fetch_and_and_8:
200 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_xor_1:
203 case Builtin::BI__sync_fetch_and_xor_2:
204 case Builtin::BI__sync_fetch_and_xor_4:
205 case Builtin::BI__sync_fetch_and_xor_8:
206 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000207 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000208 case Builtin::BI__sync_add_and_fetch_1:
209 case Builtin::BI__sync_add_and_fetch_2:
210 case Builtin::BI__sync_add_and_fetch_4:
211 case Builtin::BI__sync_add_and_fetch_8:
212 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000213 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000214 case Builtin::BI__sync_sub_and_fetch_1:
215 case Builtin::BI__sync_sub_and_fetch_2:
216 case Builtin::BI__sync_sub_and_fetch_4:
217 case Builtin::BI__sync_sub_and_fetch_8:
218 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000219 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000220 case Builtin::BI__sync_and_and_fetch_1:
221 case Builtin::BI__sync_and_and_fetch_2:
222 case Builtin::BI__sync_and_and_fetch_4:
223 case Builtin::BI__sync_and_and_fetch_8:
224 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000225 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000226 case Builtin::BI__sync_or_and_fetch_1:
227 case Builtin::BI__sync_or_and_fetch_2:
228 case Builtin::BI__sync_or_and_fetch_4:
229 case Builtin::BI__sync_or_and_fetch_8:
230 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000231 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000232 case Builtin::BI__sync_xor_and_fetch_1:
233 case Builtin::BI__sync_xor_and_fetch_2:
234 case Builtin::BI__sync_xor_and_fetch_4:
235 case Builtin::BI__sync_xor_and_fetch_8:
236 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000237 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000238 case Builtin::BI__sync_val_compare_and_swap_1:
239 case Builtin::BI__sync_val_compare_and_swap_2:
240 case Builtin::BI__sync_val_compare_and_swap_4:
241 case Builtin::BI__sync_val_compare_and_swap_8:
242 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000243 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000244 case Builtin::BI__sync_bool_compare_and_swap_1:
245 case Builtin::BI__sync_bool_compare_and_swap_2:
246 case Builtin::BI__sync_bool_compare_and_swap_4:
247 case Builtin::BI__sync_bool_compare_and_swap_8:
248 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000249 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000250 case Builtin::BI__sync_lock_test_and_set_1:
251 case Builtin::BI__sync_lock_test_and_set_2:
252 case Builtin::BI__sync_lock_test_and_set_4:
253 case Builtin::BI__sync_lock_test_and_set_8:
254 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000255 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000256 case Builtin::BI__sync_lock_release_1:
257 case Builtin::BI__sync_lock_release_2:
258 case Builtin::BI__sync_lock_release_4:
259 case Builtin::BI__sync_lock_release_8:
260 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000261 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000262 case Builtin::BI__sync_swap_1:
263 case Builtin::BI__sync_swap_2:
264 case Builtin::BI__sync_swap_4:
265 case Builtin::BI__sync_swap_8:
266 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000267 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000268#define BUILTIN(ID, TYPE, ATTRS)
269#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
270 case Builtin::BI##ID: \
271 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
272#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000273 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000274 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 return ExprError();
276 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000277 }
278
279 // Since the target specific builtins for each arch overlap, only check those
280 // of the arch we are compiling for.
281 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000282 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000283 case llvm::Triple::arm:
284 case llvm::Triple::thumb:
285 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
286 return ExprError();
287 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000288 default:
289 break;
290 }
291 }
292
293 return move(TheCallResult);
294}
295
Nate Begeman61eecf52010-06-14 05:21:25 +0000296// Get the valid immediate range for the specified NEON type code.
297static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000298 NeonTypeFlags Type(t);
299 int IsQuad = Type.isQuad();
300 switch (Type.getEltType()) {
301 case NeonTypeFlags::Int8:
302 case NeonTypeFlags::Poly8:
303 return shift ? 7 : (8 << IsQuad) - 1;
304 case NeonTypeFlags::Int16:
305 case NeonTypeFlags::Poly16:
306 return shift ? 15 : (4 << IsQuad) - 1;
307 case NeonTypeFlags::Int32:
308 return shift ? 31 : (2 << IsQuad) - 1;
309 case NeonTypeFlags::Int64:
310 return shift ? 63 : (1 << IsQuad) - 1;
311 case NeonTypeFlags::Float16:
312 assert(!shift && "cannot shift float types!");
313 return (4 << IsQuad) - 1;
314 case NeonTypeFlags::Float32:
315 assert(!shift && "cannot shift float types!");
316 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000317 }
David Blaikie7530c032012-01-17 06:56:22 +0000318 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000319}
320
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000321/// getNeonEltType - Return the QualType corresponding to the elements of
322/// the vector type specified by the NeonTypeFlags. This is used to check
323/// the pointer arguments for Neon load/store intrinsics.
324static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
325 switch (Flags.getEltType()) {
326 case NeonTypeFlags::Int8:
327 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
328 case NeonTypeFlags::Int16:
329 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
330 case NeonTypeFlags::Int32:
331 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
332 case NeonTypeFlags::Int64:
333 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
334 case NeonTypeFlags::Poly8:
335 return Context.SignedCharTy;
336 case NeonTypeFlags::Poly16:
337 return Context.ShortTy;
338 case NeonTypeFlags::Float16:
339 return Context.UnsignedShortTy;
340 case NeonTypeFlags::Float32:
341 return Context.FloatTy;
342 }
David Blaikie7530c032012-01-17 06:56:22 +0000343 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000344}
345
Nate Begeman26a31422010-06-08 02:47:44 +0000346bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000347 llvm::APSInt Result;
348
Nate Begeman0d15c532010-06-13 04:47:52 +0000349 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000350 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000351 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000352 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000353 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000354#define GET_NEON_OVERLOAD_CHECK
355#include "clang/Basic/arm_neon.inc"
356#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000357 }
358
Nate Begeman0d15c532010-06-13 04:47:52 +0000359 // For NEON intrinsics which are overloaded on vector element type, validate
360 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000362 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000364 return true;
365
Bob Wilsonda95f732011-11-08 01:16:11 +0000366 TV = Result.getLimitedValue(64);
367 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000369 << TheCall->getArg(ImmArg)->getSourceRange();
370 }
371
Bob Wilson46482552011-11-16 21:32:23 +0000372 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000373 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000374 Expr *Arg = TheCall->getArg(PtrArgNum);
375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
376 Arg = ICE->getSubExpr();
377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
378 QualType RHSTy = RHS.get()->getType();
379 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
380 if (HasConstPtr)
381 EltTy = EltTy.withConst();
382 QualType LHSTy = Context.getPointerType(EltTy);
383 AssignConvertType ConvTy;
384 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
385 if (RHS.isInvalid())
386 return true;
387 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
388 RHS.get(), AA_Assigning))
389 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000390 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000391
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 // For NEON intrinsics which take an immediate value as part of the
393 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000394 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000395 switch (BuiltinID) {
396 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000397 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
398 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000399 case ARM::BI__builtin_arm_vcvtr_f:
400 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000401#define GET_NEON_IMMEDIATE_CHECK
402#include "clang/Basic/arm_neon.inc"
403#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 };
405
Nate Begeman61eecf52010-06-14 05:21:25 +0000406 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000407 if (SemaBuiltinConstantArg(TheCall, i, Result))
408 return true;
409
Nate Begeman61eecf52010-06-14 05:21:25 +0000410 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000411 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000412 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000414 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000415
Nate Begeman99c40bb2010-08-03 21:32:34 +0000416 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000417 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000418}
Daniel Dunbarde454282008-10-02 18:44:07 +0000419
Anders Carlssond406bf02009-08-16 01:56:34 +0000420/// CheckFunctionCall - Check a direct function call for various correctness
421/// and safety properties not strictly enforced by the C type system.
422bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
423 // Get the IdentifierInfo* for the called function.
424 IdentifierInfo *FnInfo = FDecl->getIdentifier();
425
426 // None of the checks below are needed for functions that don't have
427 // simple names (e.g., C++ conversion functions).
428 if (!FnInfo)
429 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Daniel Dunbarde454282008-10-02 18:44:07 +0000431 // FIXME: This mechanism should be abstracted to be less fragile and
432 // more efficient. For example, just map function ids to custom
433 // handlers.
434
Ted Kremenekc82faca2010-09-09 04:33:05 +0000435 // Printf and scanf checking.
436 for (specific_attr_iterator<FormatAttr>
437 i = FDecl->specific_attr_begin<FormatAttr>(),
438 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000439 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Ted Kremenekc82faca2010-09-09 04:33:05 +0000442 for (specific_attr_iterator<NonNullAttr>
443 i = FDecl->specific_attr_begin<NonNullAttr>(),
444 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000445 CheckNonNullArguments(*i, TheCall->getArgs(),
446 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000447 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000448
Anna Zaks0a151a12012-01-17 00:37:07 +0000449 unsigned CMId = FDecl->getMemoryFunctionKind();
450 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000451 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000452
Anna Zaksd9b859a2012-01-13 21:52:01 +0000453 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000454 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000455 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000456 else if (CMId == Builtin::BIstrncat)
457 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000458 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000459 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000460
Anders Carlssond406bf02009-08-16 01:56:34 +0000461 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000462}
463
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000464bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
465 Expr **Args, unsigned NumArgs) {
466 for (specific_attr_iterator<FormatAttr>
467 i = Method->specific_attr_begin<FormatAttr>(),
468 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
469
470 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
471 Method->getSourceRange());
472 }
473
474 // diagnose nonnull arguments.
475 for (specific_attr_iterator<NonNullAttr>
476 i = Method->specific_attr_begin<NonNullAttr>(),
477 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
478 CheckNonNullArguments(*i, Args, lbrac);
479 }
480
481 return false;
482}
483
Anders Carlssond406bf02009-08-16 01:56:34 +0000484bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000485 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
486 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000487 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000489 QualType Ty = V->getType();
490 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000493 // format string checking.
494 for (specific_attr_iterator<FormatAttr>
495 i = NDecl->specific_attr_begin<FormatAttr>(),
496 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
497 CheckFormatArguments(*i, TheCall);
498 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000499
500 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000501}
502
Richard Smithff34d402012-04-12 05:08:17 +0000503ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
504 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000505 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
506 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000507
Richard Smithff34d402012-04-12 05:08:17 +0000508 // All these operations take one of the following forms:
509 enum {
510 // C __c11_atomic_init(A *, C)
511 Init,
512 // C __c11_atomic_load(A *, int)
513 Load,
514 // void __atomic_load(A *, CP, int)
515 Copy,
516 // C __c11_atomic_add(A *, M, int)
517 Arithmetic,
518 // C __atomic_exchange_n(A *, CP, int)
519 Xchg,
520 // void __atomic_exchange(A *, C *, CP, int)
521 GNUXchg,
522 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
523 C11CmpXchg,
524 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
525 GNUCmpXchg
526 } Form = Init;
527 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
528 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
529 // where:
530 // C is an appropriate type,
531 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
532 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
533 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
534 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000535
Richard Smithff34d402012-04-12 05:08:17 +0000536 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
537 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
538 && "need to update code for modified C11 atomics");
539 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
540 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
541 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
542 Op == AtomicExpr::AO__atomic_store_n ||
543 Op == AtomicExpr::AO__atomic_exchange_n ||
544 Op == AtomicExpr::AO__atomic_compare_exchange_n;
545 bool IsAddSub = false;
546
547 switch (Op) {
548 case AtomicExpr::AO__c11_atomic_init:
549 Form = Init;
550 break;
551
552 case AtomicExpr::AO__c11_atomic_load:
553 case AtomicExpr::AO__atomic_load_n:
554 Form = Load;
555 break;
556
557 case AtomicExpr::AO__c11_atomic_store:
558 case AtomicExpr::AO__atomic_load:
559 case AtomicExpr::AO__atomic_store:
560 case AtomicExpr::AO__atomic_store_n:
561 Form = Copy;
562 break;
563
564 case AtomicExpr::AO__c11_atomic_fetch_add:
565 case AtomicExpr::AO__c11_atomic_fetch_sub:
566 case AtomicExpr::AO__atomic_fetch_add:
567 case AtomicExpr::AO__atomic_fetch_sub:
568 case AtomicExpr::AO__atomic_add_fetch:
569 case AtomicExpr::AO__atomic_sub_fetch:
570 IsAddSub = true;
571 // Fall through.
572 case AtomicExpr::AO__c11_atomic_fetch_and:
573 case AtomicExpr::AO__c11_atomic_fetch_or:
574 case AtomicExpr::AO__c11_atomic_fetch_xor:
575 case AtomicExpr::AO__atomic_fetch_and:
576 case AtomicExpr::AO__atomic_fetch_or:
577 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000578 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000579 case AtomicExpr::AO__atomic_and_fetch:
580 case AtomicExpr::AO__atomic_or_fetch:
581 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000582 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000583 Form = Arithmetic;
584 break;
585
586 case AtomicExpr::AO__c11_atomic_exchange:
587 case AtomicExpr::AO__atomic_exchange_n:
588 Form = Xchg;
589 break;
590
591 case AtomicExpr::AO__atomic_exchange:
592 Form = GNUXchg;
593 break;
594
595 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
596 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
597 Form = C11CmpXchg;
598 break;
599
600 case AtomicExpr::AO__atomic_compare_exchange:
601 case AtomicExpr::AO__atomic_compare_exchange_n:
602 Form = GNUCmpXchg;
603 break;
604 }
605
606 // Check we have the right number of arguments.
607 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000608 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000609 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000610 << TheCall->getCallee()->getSourceRange();
611 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000612 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
613 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000614 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000615 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000616 << TheCall->getCallee()->getSourceRange();
617 return ExprError();
618 }
619
Richard Smithff34d402012-04-12 05:08:17 +0000620 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000621 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000622 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
623 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
624 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000625 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000626 << Ptr->getType() << Ptr->getSourceRange();
627 return ExprError();
628 }
629
Richard Smithff34d402012-04-12 05:08:17 +0000630 // For a __c11 builtin, this should be a pointer to an _Atomic type.
631 QualType AtomTy = pointerType->getPointeeType(); // 'A'
632 QualType ValType = AtomTy; // 'C'
633 if (IsC11) {
634 if (!AtomTy->isAtomicType()) {
635 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
636 << Ptr->getType() << Ptr->getSourceRange();
637 return ExprError();
638 }
639 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000640 }
Eli Friedman276b0612011-10-11 02:20:01 +0000641
Richard Smithff34d402012-04-12 05:08:17 +0000642 // For an arithmetic operation, the implied arithmetic must be well-formed.
643 if (Form == Arithmetic) {
644 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
645 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
646 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
647 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
648 return ExprError();
649 }
650 if (!IsAddSub && !ValType->isIntegerType()) {
651 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
652 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
653 return ExprError();
654 }
655 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
656 // For __atomic_*_n operations, the value type must be a scalar integral or
657 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000658 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000659 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
660 return ExprError();
661 }
662
663 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
664 // For GNU atomics, require a trivially-copyable type. This is not part of
665 // the GNU atomics specification, but we enforce it for sanity.
666 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000667 << Ptr->getType() << Ptr->getSourceRange();
668 return ExprError();
669 }
670
Richard Smithff34d402012-04-12 05:08:17 +0000671 // FIXME: For any builtin other than a load, the ValType must not be
672 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000673
674 switch (ValType.getObjCLifetime()) {
675 case Qualifiers::OCL_None:
676 case Qualifiers::OCL_ExplicitNone:
677 // okay
678 break;
679
680 case Qualifiers::OCL_Weak:
681 case Qualifiers::OCL_Strong:
682 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000683 // FIXME: Can this happen? By this point, ValType should be known
684 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000685 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
686 << ValType << Ptr->getSourceRange();
687 return ExprError();
688 }
689
690 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000691 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000692 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000693 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000694 ResultType = Context.BoolTy;
695
Richard Smithff34d402012-04-12 05:08:17 +0000696 // The type of a parameter passed 'by value'. In the GNU atomics, such
697 // arguments are actually passed as pointers.
698 QualType ByValType = ValType; // 'CP'
699 if (!IsC11 && !IsN)
700 ByValType = Ptr->getType();
701
Eli Friedman276b0612011-10-11 02:20:01 +0000702 // The first argument --- the pointer --- has a fixed type; we
703 // deduce the types of the rest of the arguments accordingly. Walk
704 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000705 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000706 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000707 if (i < NumVals[Form] + 1) {
708 switch (i) {
709 case 1:
710 // The second argument is the non-atomic operand. For arithmetic, this
711 // is always passed by value, and for a compare_exchange it is always
712 // passed by address. For the rest, GNU uses by-address and C11 uses
713 // by-value.
714 assert(Form != Load);
715 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
716 Ty = ValType;
717 else if (Form == Copy || Form == Xchg)
718 Ty = ByValType;
719 else if (Form == Arithmetic)
720 Ty = Context.getPointerDiffType();
721 else
722 Ty = Context.getPointerType(ValType.getUnqualifiedType());
723 break;
724 case 2:
725 // The third argument to compare_exchange / GNU exchange is a
726 // (pointer to a) desired value.
727 Ty = ByValType;
728 break;
729 case 3:
730 // The fourth argument to GNU compare_exchange is a 'weak' flag.
731 Ty = Context.BoolTy;
732 break;
733 }
Eli Friedman276b0612011-10-11 02:20:01 +0000734 } else {
735 // The order(s) are always converted to int.
736 Ty = Context.IntTy;
737 }
Richard Smithff34d402012-04-12 05:08:17 +0000738
Eli Friedman276b0612011-10-11 02:20:01 +0000739 InitializedEntity Entity =
740 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000741 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000742 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
743 if (Arg.isInvalid())
744 return true;
745 TheCall->setArg(i, Arg.get());
746 }
747
Richard Smithff34d402012-04-12 05:08:17 +0000748 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000749 SmallVector<Expr*, 5> SubExprs;
750 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000751 switch (Form) {
752 case Init:
753 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000754 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000755 break;
756 case Load:
757 SubExprs.push_back(TheCall->getArg(1)); // Order
758 break;
759 case Copy:
760 case Arithmetic:
761 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000762 SubExprs.push_back(TheCall->getArg(2)); // Order
763 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000764 break;
765 case GNUXchg:
766 // Note, AtomicExpr::getVal2() has a special case for this atomic.
767 SubExprs.push_back(TheCall->getArg(3)); // Order
768 SubExprs.push_back(TheCall->getArg(1)); // Val1
769 SubExprs.push_back(TheCall->getArg(2)); // Val2
770 break;
771 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000772 SubExprs.push_back(TheCall->getArg(3)); // Order
773 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000774 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000775 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000776 break;
777 case GNUCmpXchg:
778 SubExprs.push_back(TheCall->getArg(4)); // Order
779 SubExprs.push_back(TheCall->getArg(1)); // Val1
780 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
781 SubExprs.push_back(TheCall->getArg(2)); // Val2
782 SubExprs.push_back(TheCall->getArg(3)); // Weak
783 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000784 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000785
786 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
787 SubExprs.data(), SubExprs.size(),
788 ResultType, Op,
789 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000790}
791
792
John McCall5f8d6042011-08-27 01:09:30 +0000793/// checkBuiltinArgument - Given a call to a builtin function, perform
794/// normal type-checking on the given argument, updating the call in
795/// place. This is useful when a builtin function requires custom
796/// type-checking for some of its arguments but not necessarily all of
797/// them.
798///
799/// Returns true on error.
800static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
801 FunctionDecl *Fn = E->getDirectCallee();
802 assert(Fn && "builtin call without direct callee!");
803
804 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
805 InitializedEntity Entity =
806 InitializedEntity::InitializeParameter(S.Context, Param);
807
808 ExprResult Arg = E->getArg(0);
809 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
810 if (Arg.isInvalid())
811 return true;
812
813 E->setArg(ArgIndex, Arg.take());
814 return false;
815}
816
Chris Lattner5caa3702009-05-08 06:58:22 +0000817/// SemaBuiltinAtomicOverloaded - We have a call to a function like
818/// __sync_fetch_and_add, which is an overloaded function based on the pointer
819/// type of its first argument. The main ActOnCallExpr routines have already
820/// promoted the types of arguments because all of these calls are prototyped as
821/// void(...).
822///
823/// This function goes through and does final semantic checking for these
824/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000825ExprResult
826Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000827 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000828 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
829 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
830
831 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000832 if (TheCall->getNumArgs() < 1) {
833 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
834 << 0 << 1 << TheCall->getNumArgs()
835 << TheCall->getCallee()->getSourceRange();
836 return ExprError();
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner5caa3702009-05-08 06:58:22 +0000839 // Inspect the first argument of the atomic builtin. This should always be
840 // a pointer type, whose element is an integral scalar or pointer type.
841 // Because it is a pointer type, we don't have to worry about any implicit
842 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000843 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000844 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000845 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
846 if (FirstArgResult.isInvalid())
847 return ExprError();
848 FirstArg = FirstArgResult.take();
849 TheCall->setArg(0, FirstArg);
850
John McCallf85e1932011-06-15 23:02:42 +0000851 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
852 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000853 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
854 << FirstArg->getType() << FirstArg->getSourceRange();
855 return ExprError();
856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
John McCallf85e1932011-06-15 23:02:42 +0000858 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000859 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000860 !ValType->isBlockPointerType()) {
861 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
862 << FirstArg->getType() << FirstArg->getSourceRange();
863 return ExprError();
864 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000865
John McCallf85e1932011-06-15 23:02:42 +0000866 switch (ValType.getObjCLifetime()) {
867 case Qualifiers::OCL_None:
868 case Qualifiers::OCL_ExplicitNone:
869 // okay
870 break;
871
872 case Qualifiers::OCL_Weak:
873 case Qualifiers::OCL_Strong:
874 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000875 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000876 << ValType << FirstArg->getSourceRange();
877 return ExprError();
878 }
879
John McCallb45ae252011-10-05 07:41:44 +0000880 // Strip any qualifiers off ValType.
881 ValType = ValType.getUnqualifiedType();
882
Chandler Carruth8d13d222010-07-18 20:54:12 +0000883 // The majority of builtins return a value, but a few have special return
884 // types, so allow them to override appropriately below.
885 QualType ResultType = ValType;
886
Chris Lattner5caa3702009-05-08 06:58:22 +0000887 // We need to figure out which concrete builtin this maps onto. For example,
888 // __sync_fetch_and_add with a 2 byte object turns into
889 // __sync_fetch_and_add_2.
890#define BUILTIN_ROW(x) \
891 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
892 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Chris Lattner5caa3702009-05-08 06:58:22 +0000894 static const unsigned BuiltinIndices[][5] = {
895 BUILTIN_ROW(__sync_fetch_and_add),
896 BUILTIN_ROW(__sync_fetch_and_sub),
897 BUILTIN_ROW(__sync_fetch_and_or),
898 BUILTIN_ROW(__sync_fetch_and_and),
899 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner5caa3702009-05-08 06:58:22 +0000901 BUILTIN_ROW(__sync_add_and_fetch),
902 BUILTIN_ROW(__sync_sub_and_fetch),
903 BUILTIN_ROW(__sync_and_and_fetch),
904 BUILTIN_ROW(__sync_or_and_fetch),
905 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner5caa3702009-05-08 06:58:22 +0000907 BUILTIN_ROW(__sync_val_compare_and_swap),
908 BUILTIN_ROW(__sync_bool_compare_and_swap),
909 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000910 BUILTIN_ROW(__sync_lock_release),
911 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000912 };
Mike Stump1eb44332009-09-09 15:08:12 +0000913#undef BUILTIN_ROW
914
Chris Lattner5caa3702009-05-08 06:58:22 +0000915 // Determine the index of the size.
916 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000917 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000918 case 1: SizeIndex = 0; break;
919 case 2: SizeIndex = 1; break;
920 case 4: SizeIndex = 2; break;
921 case 8: SizeIndex = 3; break;
922 case 16: SizeIndex = 4; break;
923 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000924 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
925 << FirstArg->getType() << FirstArg->getSourceRange();
926 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattner5caa3702009-05-08 06:58:22 +0000929 // Each of these builtins has one pointer argument, followed by some number of
930 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
931 // that we ignore. Find out which row of BuiltinIndices to read from as well
932 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000933 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000934 unsigned BuiltinIndex, NumFixed = 1;
935 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000936 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000937 case Builtin::BI__sync_fetch_and_add:
938 case Builtin::BI__sync_fetch_and_add_1:
939 case Builtin::BI__sync_fetch_and_add_2:
940 case Builtin::BI__sync_fetch_and_add_4:
941 case Builtin::BI__sync_fetch_and_add_8:
942 case Builtin::BI__sync_fetch_and_add_16:
943 BuiltinIndex = 0;
944 break;
945
946 case Builtin::BI__sync_fetch_and_sub:
947 case Builtin::BI__sync_fetch_and_sub_1:
948 case Builtin::BI__sync_fetch_and_sub_2:
949 case Builtin::BI__sync_fetch_and_sub_4:
950 case Builtin::BI__sync_fetch_and_sub_8:
951 case Builtin::BI__sync_fetch_and_sub_16:
952 BuiltinIndex = 1;
953 break;
954
955 case Builtin::BI__sync_fetch_and_or:
956 case Builtin::BI__sync_fetch_and_or_1:
957 case Builtin::BI__sync_fetch_and_or_2:
958 case Builtin::BI__sync_fetch_and_or_4:
959 case Builtin::BI__sync_fetch_and_or_8:
960 case Builtin::BI__sync_fetch_and_or_16:
961 BuiltinIndex = 2;
962 break;
963
964 case Builtin::BI__sync_fetch_and_and:
965 case Builtin::BI__sync_fetch_and_and_1:
966 case Builtin::BI__sync_fetch_and_and_2:
967 case Builtin::BI__sync_fetch_and_and_4:
968 case Builtin::BI__sync_fetch_and_and_8:
969 case Builtin::BI__sync_fetch_and_and_16:
970 BuiltinIndex = 3;
971 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Douglas Gregora9766412011-11-28 16:30:08 +0000973 case Builtin::BI__sync_fetch_and_xor:
974 case Builtin::BI__sync_fetch_and_xor_1:
975 case Builtin::BI__sync_fetch_and_xor_2:
976 case Builtin::BI__sync_fetch_and_xor_4:
977 case Builtin::BI__sync_fetch_and_xor_8:
978 case Builtin::BI__sync_fetch_and_xor_16:
979 BuiltinIndex = 4;
980 break;
981
982 case Builtin::BI__sync_add_and_fetch:
983 case Builtin::BI__sync_add_and_fetch_1:
984 case Builtin::BI__sync_add_and_fetch_2:
985 case Builtin::BI__sync_add_and_fetch_4:
986 case Builtin::BI__sync_add_and_fetch_8:
987 case Builtin::BI__sync_add_and_fetch_16:
988 BuiltinIndex = 5;
989 break;
990
991 case Builtin::BI__sync_sub_and_fetch:
992 case Builtin::BI__sync_sub_and_fetch_1:
993 case Builtin::BI__sync_sub_and_fetch_2:
994 case Builtin::BI__sync_sub_and_fetch_4:
995 case Builtin::BI__sync_sub_and_fetch_8:
996 case Builtin::BI__sync_sub_and_fetch_16:
997 BuiltinIndex = 6;
998 break;
999
1000 case Builtin::BI__sync_and_and_fetch:
1001 case Builtin::BI__sync_and_and_fetch_1:
1002 case Builtin::BI__sync_and_and_fetch_2:
1003 case Builtin::BI__sync_and_and_fetch_4:
1004 case Builtin::BI__sync_and_and_fetch_8:
1005 case Builtin::BI__sync_and_and_fetch_16:
1006 BuiltinIndex = 7;
1007 break;
1008
1009 case Builtin::BI__sync_or_and_fetch:
1010 case Builtin::BI__sync_or_and_fetch_1:
1011 case Builtin::BI__sync_or_and_fetch_2:
1012 case Builtin::BI__sync_or_and_fetch_4:
1013 case Builtin::BI__sync_or_and_fetch_8:
1014 case Builtin::BI__sync_or_and_fetch_16:
1015 BuiltinIndex = 8;
1016 break;
1017
1018 case Builtin::BI__sync_xor_and_fetch:
1019 case Builtin::BI__sync_xor_and_fetch_1:
1020 case Builtin::BI__sync_xor_and_fetch_2:
1021 case Builtin::BI__sync_xor_and_fetch_4:
1022 case Builtin::BI__sync_xor_and_fetch_8:
1023 case Builtin::BI__sync_xor_and_fetch_16:
1024 BuiltinIndex = 9;
1025 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001028 case Builtin::BI__sync_val_compare_and_swap_1:
1029 case Builtin::BI__sync_val_compare_and_swap_2:
1030 case Builtin::BI__sync_val_compare_and_swap_4:
1031 case Builtin::BI__sync_val_compare_and_swap_8:
1032 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001033 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 NumFixed = 2;
1035 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001036
Chris Lattner5caa3702009-05-08 06:58:22 +00001037 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001038 case Builtin::BI__sync_bool_compare_and_swap_1:
1039 case Builtin::BI__sync_bool_compare_and_swap_2:
1040 case Builtin::BI__sync_bool_compare_and_swap_4:
1041 case Builtin::BI__sync_bool_compare_and_swap_8:
1042 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001043 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001044 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001045 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001046 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001047
1048 case Builtin::BI__sync_lock_test_and_set:
1049 case Builtin::BI__sync_lock_test_and_set_1:
1050 case Builtin::BI__sync_lock_test_and_set_2:
1051 case Builtin::BI__sync_lock_test_and_set_4:
1052 case Builtin::BI__sync_lock_test_and_set_8:
1053 case Builtin::BI__sync_lock_test_and_set_16:
1054 BuiltinIndex = 12;
1055 break;
1056
Chris Lattner5caa3702009-05-08 06:58:22 +00001057 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001058 case Builtin::BI__sync_lock_release_1:
1059 case Builtin::BI__sync_lock_release_2:
1060 case Builtin::BI__sync_lock_release_4:
1061 case Builtin::BI__sync_lock_release_8:
1062 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001063 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001064 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001065 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001066 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001067
1068 case Builtin::BI__sync_swap:
1069 case Builtin::BI__sync_swap_1:
1070 case Builtin::BI__sync_swap_2:
1071 case Builtin::BI__sync_swap_4:
1072 case Builtin::BI__sync_swap_8:
1073 case Builtin::BI__sync_swap_16:
1074 BuiltinIndex = 14;
1075 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chris Lattner5caa3702009-05-08 06:58:22 +00001078 // Now that we know how many fixed arguments we expect, first check that we
1079 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001080 if (TheCall->getNumArgs() < 1+NumFixed) {
1081 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1082 << 0 << 1+NumFixed << TheCall->getNumArgs()
1083 << TheCall->getCallee()->getSourceRange();
1084 return ExprError();
1085 }
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001087 // Get the decl for the concrete builtin from this, we can tell what the
1088 // concrete integer type we should convert to is.
1089 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1090 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1091 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001092 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001093 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1094 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001095
John McCallf871d0c2010-08-07 06:22:56 +00001096 // The first argument --- the pointer --- has a fixed type; we
1097 // deduce the types of the rest of the arguments accordingly. Walk
1098 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001099 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001100 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Chris Lattner5caa3702009-05-08 06:58:22 +00001102 // GCC does an implicit conversion to the pointer or integer ValType. This
1103 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001104 // Initialize the argument.
1105 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1106 ValType, /*consume*/ false);
1107 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001108 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001109 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner5caa3702009-05-08 06:58:22 +00001111 // Okay, we have something that *can* be converted to the right type. Check
1112 // to see if there is a potentially weird extension going on here. This can
1113 // happen when you do an atomic operation on something like an char* and
1114 // pass in 42. The 42 gets converted to char. This is even more strange
1115 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001116 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001117 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001120 ASTContext& Context = this->getASTContext();
1121
1122 // Create a new DeclRefExpr to refer to the new decl.
1123 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1124 Context,
1125 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001126 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001127 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001128 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001129 DRE->getLocation(),
1130 NewBuiltinDecl->getType(),
1131 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner5caa3702009-05-08 06:58:22 +00001133 // Set the callee in the CallExpr.
1134 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001135 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001136 if (PromotedCall.isInvalid())
1137 return ExprError();
1138 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001140 // Change the result type of the call to match the original value type. This
1141 // is arbitrary, but the codegen for these builtins ins design to handle it
1142 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001143 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001144
1145 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001146}
1147
Chris Lattner69039812009-02-18 06:01:06 +00001148/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001149/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001150/// Note: It might also make sense to do the UTF-16 conversion here (would
1151/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001152bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001153 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001154 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1155
Douglas Gregor5cee1192011-07-27 05:40:30 +00001156 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001157 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1158 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001159 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001162 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001163 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001164 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001165 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001166 const UTF8 *FromPtr = (UTF8 *)String.data();
1167 UTF16 *ToPtr = &ToBuf[0];
1168
1169 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1170 &ToPtr, ToPtr + NumBytes,
1171 strictConversion);
1172 // Check for conversion failure.
1173 if (Result != conversionOK)
1174 Diag(Arg->getLocStart(),
1175 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1176 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001177 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001178}
1179
Chris Lattnerc27c6652007-12-20 00:05:45 +00001180/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1181/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001182bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1183 Expr *Fn = TheCall->getCallee();
1184 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001185 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001186 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001187 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1188 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001189 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001190 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001191 return true;
1192 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001193
1194 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001195 return Diag(TheCall->getLocEnd(),
1196 diag::err_typecheck_call_too_few_args_at_least)
1197 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001198 }
1199
John McCall5f8d6042011-08-27 01:09:30 +00001200 // Type-check the first argument normally.
1201 if (checkBuiltinArgument(*this, TheCall, 0))
1202 return true;
1203
Chris Lattnerc27c6652007-12-20 00:05:45 +00001204 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001205 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001206 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001207 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001208 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001209 else if (FunctionDecl *FD = getCurFunctionDecl())
1210 isVariadic = FD->isVariadic();
1211 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001212 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Chris Lattnerc27c6652007-12-20 00:05:45 +00001214 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001215 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1216 return true;
1217 }
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Chris Lattner30ce3442007-12-19 23:59:04 +00001219 // Verify that the second argument to the builtin is the last argument of the
1220 // current function or method.
1221 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001222 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Anders Carlsson88cf2262008-02-11 04:20:54 +00001224 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1225 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001226 // FIXME: This isn't correct for methods (results in bogus warning).
1227 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001228 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001229 if (CurBlock)
1230 LastArg = *(CurBlock->TheDecl->param_end()-1);
1231 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001232 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001233 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001234 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001235 SecondArgIsLastNamedArgument = PV == LastArg;
1236 }
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner30ce3442007-12-19 23:59:04 +00001239 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001240 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001241 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1242 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001243}
Chris Lattner30ce3442007-12-19 23:59:04 +00001244
Chris Lattner1b9a0792007-12-20 00:26:33 +00001245/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1246/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001247bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1248 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001249 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001250 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001251 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001252 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001253 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001254 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001255 << SourceRange(TheCall->getArg(2)->getLocStart(),
1256 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001257
John Wiegley429bb272011-04-08 18:41:53 +00001258 ExprResult OrigArg0 = TheCall->getArg(0);
1259 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001260
Chris Lattner1b9a0792007-12-20 00:26:33 +00001261 // Do standard promotions between the two arguments, returning their common
1262 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001263 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001264 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1265 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001266
1267 // Make sure any conversions are pushed back into the call; this is
1268 // type safe since unordered compare builtins are declared as "_Bool
1269 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001270 TheCall->setArg(0, OrigArg0.get());
1271 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001272
John Wiegley429bb272011-04-08 18:41:53 +00001273 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001274 return false;
1275
Chris Lattner1b9a0792007-12-20 00:26:33 +00001276 // If the common type isn't a real floating type, then the arguments were
1277 // invalid for this operation.
1278 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001279 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001280 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001281 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1282 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Chris Lattner1b9a0792007-12-20 00:26:33 +00001284 return false;
1285}
1286
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001287/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1288/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001289/// to check everything. We expect the last argument to be a floating point
1290/// value.
1291bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1292 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001293 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001294 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001295 if (TheCall->getNumArgs() > NumArgs)
1296 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001297 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001298 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001299 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001300 (*(TheCall->arg_end()-1))->getLocEnd());
1301
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001302 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Eli Friedman9ac6f622009-08-31 20:06:00 +00001304 if (OrigArg->isTypeDependent())
1305 return false;
1306
Chris Lattner81368fb2010-05-06 05:50:07 +00001307 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001308 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001309 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001310 diag::err_typecheck_call_invalid_unary_fp)
1311 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Chris Lattner81368fb2010-05-06 05:50:07 +00001313 // If this is an implicit conversion from float -> double, remove it.
1314 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1315 Expr *CastArg = Cast->getSubExpr();
1316 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1317 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1318 "promotion from float to double is the only expected cast here");
1319 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001320 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001321 }
1322 }
1323
Eli Friedman9ac6f622009-08-31 20:06:00 +00001324 return false;
1325}
1326
Eli Friedmand38617c2008-05-14 19:38:39 +00001327/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1328// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001329ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001330 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001331 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001332 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001333 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001334 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001335
Nate Begeman37b6a572010-06-08 00:16:34 +00001336 // Determine which of the following types of shufflevector we're checking:
1337 // 1) unary, vector mask: (lhs, mask)
1338 // 2) binary, vector mask: (lhs, rhs, mask)
1339 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1340 QualType resType = TheCall->getArg(0)->getType();
1341 unsigned numElements = 0;
1342
Douglas Gregorcde01732009-05-19 22:10:17 +00001343 if (!TheCall->getArg(0)->isTypeDependent() &&
1344 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001345 QualType LHSType = TheCall->getArg(0)->getType();
1346 QualType RHSType = TheCall->getArg(1)->getType();
1347
1348 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001349 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001350 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001351 TheCall->getArg(1)->getLocEnd());
1352 return ExprError();
1353 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001354
1355 numElements = LHSType->getAs<VectorType>()->getNumElements();
1356 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Nate Begeman37b6a572010-06-08 00:16:34 +00001358 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1359 // with mask. If so, verify that RHS is an integer vector type with the
1360 // same number of elts as lhs.
1361 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001362 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001363 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1364 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1365 << SourceRange(TheCall->getArg(1)->getLocStart(),
1366 TheCall->getArg(1)->getLocEnd());
1367 numResElements = numElements;
1368 }
1369 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001370 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001371 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001372 TheCall->getArg(1)->getLocEnd());
1373 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001374 } else if (numElements != numResElements) {
1375 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001376 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001377 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001378 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001379 }
1380
1381 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001382 if (TheCall->getArg(i)->isTypeDependent() ||
1383 TheCall->getArg(i)->isValueDependent())
1384 continue;
1385
Nate Begeman37b6a572010-06-08 00:16:34 +00001386 llvm::APSInt Result(32);
1387 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1388 return ExprError(Diag(TheCall->getLocStart(),
1389 diag::err_shufflevector_nonconstant_argument)
1390 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001391
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001392 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001393 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001394 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001395 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001396 }
1397
Chris Lattner5f9e2722011-07-23 10:55:15 +00001398 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001399
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001400 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001401 exprs.push_back(TheCall->getArg(i));
1402 TheCall->setArg(i, 0);
1403 }
1404
Nate Begemana88dc302009-08-12 02:10:25 +00001405 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001406 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001407 TheCall->getCallee()->getLocStart(),
1408 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001409}
Chris Lattner30ce3442007-12-19 23:59:04 +00001410
Daniel Dunbar4493f792008-07-21 22:59:13 +00001411/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1412// This is declared to take (const void*, ...) and can take two
1413// optional constant int args.
1414bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001415 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001416
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001418 return Diag(TheCall->getLocEnd(),
1419 diag::err_typecheck_call_too_many_args_at_most)
1420 << 0 /*function call*/ << 3 << NumArgs
1421 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001422
1423 // Argument 0 is checked for us and the remaining arguments must be
1424 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001425 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001426 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001427
Eli Friedman9aef7262009-12-04 00:30:06 +00001428 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001429 if (SemaBuiltinConstantArg(TheCall, i, Result))
1430 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Daniel Dunbar4493f792008-07-21 22:59:13 +00001432 // FIXME: gcc issues a warning and rewrites these to 0. These
1433 // seems especially odd for the third argument since the default
1434 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001435 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001436 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001437 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001438 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001439 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001440 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001442 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001443 }
1444 }
1445
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001446 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001447}
1448
Eric Christopher691ebc32010-04-17 02:26:23 +00001449/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1450/// TheCall is a constant expression.
1451bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1452 llvm::APSInt &Result) {
1453 Expr *Arg = TheCall->getArg(ArgNum);
1454 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1455 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1456
1457 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1458
1459 if (!Arg->isIntegerConstantExpr(Result, Context))
1460 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001461 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001462
Chris Lattner21fb98e2009-09-23 06:06:36 +00001463 return false;
1464}
1465
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001466/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1467/// int type). This simply type checks that type is one of the defined
1468/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001469// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001470bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001471 llvm::APSInt Result;
1472
1473 // Check constant-ness first.
1474 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1475 return true;
1476
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001477 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001478 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001479 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1480 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001481 }
1482
1483 return false;
1484}
1485
Eli Friedman586d6a82009-05-03 06:04:26 +00001486/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001487/// This checks that val is a constant 1.
1488bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1489 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001490 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001491
Eric Christopher691ebc32010-04-17 02:26:23 +00001492 // TODO: This is less than ideal. Overload this to take a value.
1493 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1494 return true;
1495
1496 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001497 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1498 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1499
1500 return false;
1501}
1502
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001503// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001504bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1505 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001506 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001507 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001508 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001509 if (E->isTypeDependent() || E->isValueDependent())
1510 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001511
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001512 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001513
David Blaikiea73cdcb2012-02-10 21:07:25 +00001514 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1515 // Technically -Wformat-nonliteral does not warn about this case.
1516 // The behavior of printf and friends in this case is implementation
1517 // dependent. Ideally if the format string cannot be null then
1518 // it should have a 'nonnull' attribute in the function prototype.
1519 return true;
1520
Ted Kremenekd30ef872009-01-12 23:09:09 +00001521 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001522 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001523 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001524 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001525 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001526 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001527 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001528 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1529 format_idx, firstDataArg, Type,
1530 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001531 }
1532
1533 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001534 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1535 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001536 }
1537
John McCall56ca35d2011-02-17 10:25:35 +00001538 case Stmt::OpaqueValueExprClass:
1539 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1540 E = src;
1541 goto tryAgain;
1542 }
1543 return false;
1544
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001545 case Stmt::PredefinedExprClass:
1546 // While __func__, etc., are technically not string literals, they
1547 // cannot contain format specifiers and thus are not a security
1548 // liability.
1549 return true;
1550
Ted Kremenek082d9362009-03-20 21:35:28 +00001551 case Stmt::DeclRefExprClass: {
1552 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Ted Kremenek082d9362009-03-20 21:35:28 +00001554 // As an exception, do not flag errors for variables binding to
1555 // const string literals.
1556 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1557 bool isConstant = false;
1558 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001559
Ted Kremenek082d9362009-03-20 21:35:28 +00001560 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1561 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001562 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001563 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001564 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001565 } else if (T->isObjCObjectPointerType()) {
1566 // In ObjC, there is usually no "const ObjectPointer" type,
1567 // so don't check if the pointee type is constant.
1568 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Ted Kremenek082d9362009-03-20 21:35:28 +00001571 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001572 if (const Expr *Init = VD->getAnyInitializer()) {
1573 // Look through initializers like const char c[] = { "foo" }
1574 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1575 if (InitList->isStringLiteralInit())
1576 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1577 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001578 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001579 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001580 Type, /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001581 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Anders Carlssond966a552009-06-28 19:55:58 +00001584 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1585 // special check to see if the format string is a function parameter
1586 // of the function calling the printf function. If the function
1587 // has an attribute indicating it is a printf-like function, then we
1588 // should suppress warnings concerning non-literals being used in a call
1589 // to a vprintf function. For example:
1590 //
1591 // void
1592 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1593 // va_list ap;
1594 // va_start(ap, fmt);
1595 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1596 // ...
1597 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001598 if (HasVAListArg) {
1599 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1600 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1601 int PVIndex = PV->getFunctionScopeIndex() + 1;
1602 for (specific_attr_iterator<FormatAttr>
1603 i = ND->specific_attr_begin<FormatAttr>(),
1604 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1605 FormatAttr *PVFormat = *i;
1606 // adjust for implicit parameter
1607 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1608 if (MD->isInstance())
1609 ++PVIndex;
1610 // We also check if the formats are compatible.
1611 // We can't pass a 'scanf' string to a 'printf' function.
1612 if (PVIndex == PVFormat->getFormatIdx() &&
1613 Type == GetFormatStringType(PVFormat))
1614 return true;
1615 }
1616 }
1617 }
1618 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Ted Kremenek082d9362009-03-20 21:35:28 +00001621 return false;
1622 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001623
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001624 case Stmt::CallExprClass:
1625 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001626 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001627 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1628 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1629 unsigned ArgIndex = FA->getFormatIdx();
1630 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1631 if (MD->isInstance())
1632 --ArgIndex;
1633 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001635 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1636 format_idx, firstDataArg, Type,
1637 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001638 }
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Anders Carlsson8f031b32009-06-27 04:05:33 +00001641 return false;
1642 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001643 case Stmt::ObjCStringLiteralClass:
1644 case Stmt::StringLiteralClass: {
1645 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Ted Kremenek082d9362009-03-20 21:35:28 +00001647 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001648 StrE = ObjCFExpr->getString();
1649 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001650 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Ted Kremenekd30ef872009-01-12 23:09:09 +00001652 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001653 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001654 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001655 return true;
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Ted Kremenekd30ef872009-01-12 23:09:09 +00001658 return false;
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Ted Kremenek082d9362009-03-20 21:35:28 +00001661 default:
1662 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001663 }
1664}
1665
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001666void
Mike Stump1eb44332009-09-09 15:08:12 +00001667Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001668 const Expr * const *ExprArgs,
1669 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001670 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1671 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001672 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001673 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001674 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001675 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001676 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001677 }
1678}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001679
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001680Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1681 return llvm::StringSwitch<FormatStringType>(Format->getType())
1682 .Case("scanf", FST_Scanf)
1683 .Cases("printf", "printf0", FST_Printf)
1684 .Cases("NSString", "CFString", FST_NSString)
1685 .Case("strftime", FST_Strftime)
1686 .Case("strfmon", FST_Strfmon)
1687 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1688 .Default(FST_Unknown);
1689}
1690
Ted Kremenek826a3452010-07-16 02:11:22 +00001691/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1692/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001693void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1694 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001695 // The way the format attribute works in GCC, the implicit this argument
1696 // of member functions is counted. However, it doesn't appear in our own
1697 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001698 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001699 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1700 IsCXXMember, TheCall->getRParenLoc(),
1701 TheCall->getCallee()->getSourceRange());
1702}
1703
1704void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1705 unsigned NumArgs, bool IsCXXMember,
1706 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001707 bool HasVAListArg = Format->getFirstArg() == 0;
1708 unsigned format_idx = Format->getFormatIdx() - 1;
1709 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1710 if (IsCXXMember) {
1711 if (format_idx == 0)
1712 return;
1713 --format_idx;
1714 if(firstDataArg != 0)
1715 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001716 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001717 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1718 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001719}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001720
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001721void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1722 bool HasVAListArg, unsigned format_idx,
1723 unsigned firstDataArg, FormatStringType Type,
1724 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001725 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001726 if (format_idx >= NumArgs) {
1727 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001728 return;
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001731 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Chris Lattner59907c42007-08-10 20:18:51 +00001733 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001734 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001735 // Dynamically generated format strings are difficult to
1736 // automatically vet at compile time. Requiring that format strings
1737 // are string literals: (1) permits the checking of format strings by
1738 // the compiler and thereby (2) can practically remove the source of
1739 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001740
Mike Stump1eb44332009-09-09 15:08:12 +00001741 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001742 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001743 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001744 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001745 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001746 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001747 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001748
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001749 // Strftime is particular as it always uses a single 'time' argument,
1750 // so it is safe to pass a non-literal string.
1751 if (Type == FST_Strftime)
1752 return;
1753
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001754 // Do not emit diag when the string param is a macro expansion and the
1755 // format is either NSString or CFString. This is a hack to prevent
1756 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1757 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001758 if (Type == FST_NSString &&
1759 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001760 return;
1761
Chris Lattner655f1412009-04-29 04:59:47 +00001762 // If there are no arguments specified, warn with -Wformat-security, otherwise
1763 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001764 if (NumArgs == format_idx+1)
1765 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001766 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001767 << OrigFormatExpr->getSourceRange();
1768 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001769 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001770 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001771 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001772}
Ted Kremenek71895b92007-08-14 17:39:48 +00001773
Ted Kremeneke0e53132010-01-28 23:39:18 +00001774namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001775class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1776protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001777 Sema &S;
1778 const StringLiteral *FExpr;
1779 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001780 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001781 const unsigned NumDataArgs;
1782 const bool IsObjCLiteral;
1783 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001784 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001785 const Expr * const *Args;
1786 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001787 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001788 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001789 bool usesPositionalArgs;
1790 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001791 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001792public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001793 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001794 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001795 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001796 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001797 Expr **args, unsigned numArgs,
1798 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001799 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001800 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001801 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001802 IsObjCLiteral(isObjCLiteral), Beg(beg),
1803 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001804 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001805 usesPositionalArgs(false), atFirstArg(true),
1806 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001807 CoveredArgs.resize(numDataArgs);
1808 CoveredArgs.reset();
1809 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001810
Ted Kremenek07d161f2010-01-29 01:50:07 +00001811 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001812
Ted Kremenek826a3452010-07-16 02:11:22 +00001813 void HandleIncompleteSpecifier(const char *startSpecifier,
1814 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001815
1816 void HandleNonStandardLengthModifier(
1817 const analyze_format_string::LengthModifier &LM,
1818 const char *startSpecifier, unsigned specifierLen);
1819
1820 void HandleNonStandardConversionSpecifier(
1821 const analyze_format_string::ConversionSpecifier &CS,
1822 const char *startSpecifier, unsigned specifierLen);
1823
1824 void HandleNonStandardConversionSpecification(
1825 const analyze_format_string::LengthModifier &LM,
1826 const analyze_format_string::ConversionSpecifier &CS,
1827 const char *startSpecifier, unsigned specifierLen);
1828
Hans Wennborgf8562642012-03-09 10:10:54 +00001829 virtual void HandlePosition(const char *startPos, unsigned posLen);
1830
Ted Kremenekefaff192010-02-27 01:41:03 +00001831 virtual void HandleInvalidPosition(const char *startSpecifier,
1832 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001833 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001834
1835 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1836
Ted Kremeneke0e53132010-01-28 23:39:18 +00001837 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001838
Richard Trieu55733de2011-10-28 00:41:25 +00001839 template <typename Range>
1840 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1841 const Expr *ArgumentExpr,
1842 PartialDiagnostic PDiag,
1843 SourceLocation StringLoc,
1844 bool IsStringLocation, Range StringRange,
1845 FixItHint Fixit = FixItHint());
1846
Ted Kremenek826a3452010-07-16 02:11:22 +00001847protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001848 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1849 const char *startSpec,
1850 unsigned specifierLen,
1851 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001852
1853 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1854 const char *startSpec,
1855 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001856
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001857 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001858 CharSourceRange getSpecifierRange(const char *startSpecifier,
1859 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001860 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001861
Ted Kremenek0d277352010-01-29 01:06:55 +00001862 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001863
1864 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1865 const analyze_format_string::ConversionSpecifier &CS,
1866 const char *startSpecifier, unsigned specifierLen,
1867 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001868
1869 template <typename Range>
1870 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1871 bool IsStringLocation, Range StringRange,
1872 FixItHint Fixit = FixItHint());
1873
1874 void CheckPositionalAndNonpositionalArgs(
1875 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001876};
1877}
1878
Ted Kremenek826a3452010-07-16 02:11:22 +00001879SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001880 return OrigFormatExpr->getSourceRange();
1881}
1882
Ted Kremenek826a3452010-07-16 02:11:22 +00001883CharSourceRange CheckFormatHandler::
1884getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001885 SourceLocation Start = getLocationOfByte(startSpecifier);
1886 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1887
1888 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001889 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001890
1891 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001892}
1893
Ted Kremenek826a3452010-07-16 02:11:22 +00001894SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001895 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001896}
1897
Ted Kremenek826a3452010-07-16 02:11:22 +00001898void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1899 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1901 getLocationOfByte(startSpecifier),
1902 /*IsStringLocation*/true,
1903 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001904}
1905
Hans Wennborg76517422012-02-22 10:17:01 +00001906void CheckFormatHandler::HandleNonStandardLengthModifier(
1907 const analyze_format_string::LengthModifier &LM,
1908 const char *startSpecifier, unsigned specifierLen) {
1909 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001910 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001911 getLocationOfByte(LM.getStart()),
1912 /*IsStringLocation*/true,
1913 getSpecifierRange(startSpecifier, specifierLen));
1914}
1915
1916void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1917 const analyze_format_string::ConversionSpecifier &CS,
1918 const char *startSpecifier, unsigned specifierLen) {
1919 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001920 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001921 getLocationOfByte(CS.getStart()),
1922 /*IsStringLocation*/true,
1923 getSpecifierRange(startSpecifier, specifierLen));
1924}
1925
1926void CheckFormatHandler::HandleNonStandardConversionSpecification(
1927 const analyze_format_string::LengthModifier &LM,
1928 const analyze_format_string::ConversionSpecifier &CS,
1929 const char *startSpecifier, unsigned specifierLen) {
1930 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1931 << LM.toString() << CS.toString(),
1932 getLocationOfByte(LM.getStart()),
1933 /*IsStringLocation*/true,
1934 getSpecifierRange(startSpecifier, specifierLen));
1935}
1936
Hans Wennborgf8562642012-03-09 10:10:54 +00001937void CheckFormatHandler::HandlePosition(const char *startPos,
1938 unsigned posLen) {
1939 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1940 getLocationOfByte(startPos),
1941 /*IsStringLocation*/true,
1942 getSpecifierRange(startPos, posLen));
1943}
1944
Ted Kremenekefaff192010-02-27 01:41:03 +00001945void
Ted Kremenek826a3452010-07-16 02:11:22 +00001946CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1947 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1949 << (unsigned) p,
1950 getLocationOfByte(startPos), /*IsStringLocation*/true,
1951 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001952}
1953
Ted Kremenek826a3452010-07-16 02:11:22 +00001954void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001955 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001956 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1957 getLocationOfByte(startPos),
1958 /*IsStringLocation*/true,
1959 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001960}
1961
Ted Kremenek826a3452010-07-16 02:11:22 +00001962void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001963 if (!IsObjCLiteral) {
1964 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001965 EmitFormatDiagnostic(
1966 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1967 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1968 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001969 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001970}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001971
Ted Kremenek826a3452010-07-16 02:11:22 +00001972const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001973 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001974}
1975
1976void CheckFormatHandler::DoneProcessing() {
1977 // Does the number of data arguments exceed the number of
1978 // format conversions in the format string?
1979 if (!HasVAListArg) {
1980 // Find any arguments that weren't covered.
1981 CoveredArgs.flip();
1982 signed notCoveredArg = CoveredArgs.find_first();
1983 if (notCoveredArg >= 0) {
1984 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00001985 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
1986 if (!S.getSourceManager().isInSystemMacro(Loc)) {
1987 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1988 Loc,
1989 /*IsStringLocation*/false, getFormatStringRange());
1990 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001991 }
1992 }
1993}
1994
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001995bool
1996CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1997 SourceLocation Loc,
1998 const char *startSpec,
1999 unsigned specifierLen,
2000 const char *csStart,
2001 unsigned csLen) {
2002
2003 bool keepGoing = true;
2004 if (argIndex < NumDataArgs) {
2005 // Consider the argument coverered, even though the specifier doesn't
2006 // make sense.
2007 CoveredArgs.set(argIndex);
2008 }
2009 else {
2010 // If argIndex exceeds the number of data arguments we
2011 // don't issue a warning because that is just a cascade of warnings (and
2012 // they may have intended '%%' anyway). We don't want to continue processing
2013 // the format string after this point, however, as we will like just get
2014 // gibberish when trying to match arguments.
2015 keepGoing = false;
2016 }
2017
Richard Trieu55733de2011-10-28 00:41:25 +00002018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2019 << StringRef(csStart, csLen),
2020 Loc, /*IsStringLocation*/true,
2021 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002022
2023 return keepGoing;
2024}
2025
Richard Trieu55733de2011-10-28 00:41:25 +00002026void
2027CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2028 const char *startSpec,
2029 unsigned specifierLen) {
2030 EmitFormatDiagnostic(
2031 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2032 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2033}
2034
Ted Kremenek666a1972010-07-26 19:45:42 +00002035bool
2036CheckFormatHandler::CheckNumArgs(
2037 const analyze_format_string::FormatSpecifier &FS,
2038 const analyze_format_string::ConversionSpecifier &CS,
2039 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2040
2041 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002042 PartialDiagnostic PDiag = FS.usesPositionalArg()
2043 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2044 << (argIndex+1) << NumDataArgs)
2045 : S.PDiag(diag::warn_printf_insufficient_data_args);
2046 EmitFormatDiagnostic(
2047 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2048 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002049 return false;
2050 }
2051 return true;
2052}
2053
Richard Trieu55733de2011-10-28 00:41:25 +00002054template<typename Range>
2055void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2056 SourceLocation Loc,
2057 bool IsStringLocation,
2058 Range StringRange,
2059 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002060 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002061 Loc, IsStringLocation, StringRange, FixIt);
2062}
2063
2064/// \brief If the format string is not within the funcion call, emit a note
2065/// so that the function call and string are in diagnostic messages.
2066///
2067/// \param inFunctionCall if true, the format string is within the function
2068/// call and only one diagnostic message will be produced. Otherwise, an
2069/// extra note will be emitted pointing to location of the format string.
2070///
2071/// \param ArgumentExpr the expression that is passed as the format string
2072/// argument in the function call. Used for getting locations when two
2073/// diagnostics are emitted.
2074///
2075/// \param PDiag the callee should already have provided any strings for the
2076/// diagnostic message. This function only adds locations and fixits
2077/// to diagnostics.
2078///
2079/// \param Loc primary location for diagnostic. If two diagnostics are
2080/// required, one will be at Loc and a new SourceLocation will be created for
2081/// the other one.
2082///
2083/// \param IsStringLocation if true, Loc points to the format string should be
2084/// used for the note. Otherwise, Loc points to the argument list and will
2085/// be used with PDiag.
2086///
2087/// \param StringRange some or all of the string to highlight. This is
2088/// templated so it can accept either a CharSourceRange or a SourceRange.
2089///
2090/// \param Fixit optional fix it hint for the format string.
2091template<typename Range>
2092void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2093 const Expr *ArgumentExpr,
2094 PartialDiagnostic PDiag,
2095 SourceLocation Loc,
2096 bool IsStringLocation,
2097 Range StringRange,
2098 FixItHint FixIt) {
2099 if (InFunctionCall)
2100 S.Diag(Loc, PDiag) << StringRange << FixIt;
2101 else {
2102 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2103 << ArgumentExpr->getSourceRange();
2104 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2105 diag::note_format_string_defined)
2106 << StringRange << FixIt;
2107 }
2108}
2109
Ted Kremenek826a3452010-07-16 02:11:22 +00002110//===--- CHECK: Printf format string checking ------------------------------===//
2111
2112namespace {
2113class CheckPrintfHandler : public CheckFormatHandler {
2114public:
2115 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2116 const Expr *origFormatExpr, unsigned firstDataArg,
2117 unsigned numDataArgs, bool isObjCLiteral,
2118 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002119 Expr **Args, unsigned NumArgs,
2120 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002121 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2122 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002123 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002124
2125
2126 bool HandleInvalidPrintfConversionSpecifier(
2127 const analyze_printf::PrintfSpecifier &FS,
2128 const char *startSpecifier,
2129 unsigned specifierLen);
2130
2131 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2132 const char *startSpecifier,
2133 unsigned specifierLen);
2134
2135 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2136 const char *startSpecifier, unsigned specifierLen);
2137 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2138 const analyze_printf::OptionalAmount &Amt,
2139 unsigned type,
2140 const char *startSpecifier, unsigned specifierLen);
2141 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2142 const analyze_printf::OptionalFlag &flag,
2143 const char *startSpecifier, unsigned specifierLen);
2144 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2145 const analyze_printf::OptionalFlag &ignoredFlag,
2146 const analyze_printf::OptionalFlag &flag,
2147 const char *startSpecifier, unsigned specifierLen);
2148};
2149}
2150
2151bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2152 const analyze_printf::PrintfSpecifier &FS,
2153 const char *startSpecifier,
2154 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002155 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002156 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002157
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002158 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2159 getLocationOfByte(CS.getStart()),
2160 startSpecifier, specifierLen,
2161 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002162}
2163
Ted Kremenek826a3452010-07-16 02:11:22 +00002164bool CheckPrintfHandler::HandleAmount(
2165 const analyze_format_string::OptionalAmount &Amt,
2166 unsigned k, const char *startSpecifier,
2167 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002168
2169 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002170 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002171 unsigned argIndex = Amt.getArgIndex();
2172 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002173 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2174 << k,
2175 getLocationOfByte(Amt.getStart()),
2176 /*IsStringLocation*/true,
2177 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002178 // Don't do any more checking. We will just emit
2179 // spurious errors.
2180 return false;
2181 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002182
Ted Kremenek0d277352010-01-29 01:06:55 +00002183 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002184 // Although not in conformance with C99, we also allow the argument to be
2185 // an 'unsigned int' as that is a reasonably safe case. GCC also
2186 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002187 CoveredArgs.set(argIndex);
2188 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002189 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002190
2191 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2192 assert(ATR.isValid());
2193
2194 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002195 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002196 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002197 << T << Arg->getSourceRange(),
2198 getLocationOfByte(Amt.getStart()),
2199 /*IsStringLocation*/true,
2200 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002201 // Don't do any more checking. We will just emit
2202 // spurious errors.
2203 return false;
2204 }
2205 }
2206 }
2207 return true;
2208}
Ted Kremenek0d277352010-01-29 01:06:55 +00002209
Tom Caree4ee9662010-06-17 19:00:27 +00002210void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002211 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002212 const analyze_printf::OptionalAmount &Amt,
2213 unsigned type,
2214 const char *startSpecifier,
2215 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002216 const analyze_printf::PrintfConversionSpecifier &CS =
2217 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002218
Richard Trieu55733de2011-10-28 00:41:25 +00002219 FixItHint fixit =
2220 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2221 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2222 Amt.getConstantLength()))
2223 : FixItHint();
2224
2225 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2226 << type << CS.toString(),
2227 getLocationOfByte(Amt.getStart()),
2228 /*IsStringLocation*/true,
2229 getSpecifierRange(startSpecifier, specifierLen),
2230 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002231}
2232
Ted Kremenek826a3452010-07-16 02:11:22 +00002233void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002234 const analyze_printf::OptionalFlag &flag,
2235 const char *startSpecifier,
2236 unsigned specifierLen) {
2237 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002238 const analyze_printf::PrintfConversionSpecifier &CS =
2239 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002240 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2241 << flag.toString() << CS.toString(),
2242 getLocationOfByte(flag.getPosition()),
2243 /*IsStringLocation*/true,
2244 getSpecifierRange(startSpecifier, specifierLen),
2245 FixItHint::CreateRemoval(
2246 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002247}
2248
2249void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002250 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002251 const analyze_printf::OptionalFlag &ignoredFlag,
2252 const analyze_printf::OptionalFlag &flag,
2253 const char *startSpecifier,
2254 unsigned specifierLen) {
2255 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002256 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2257 << ignoredFlag.toString() << flag.toString(),
2258 getLocationOfByte(ignoredFlag.getPosition()),
2259 /*IsStringLocation*/true,
2260 getSpecifierRange(startSpecifier, specifierLen),
2261 FixItHint::CreateRemoval(
2262 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002263}
2264
Ted Kremeneke0e53132010-01-28 23:39:18 +00002265bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002266CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002267 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002268 const char *startSpecifier,
2269 unsigned specifierLen) {
2270
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002271 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002272 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002273 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002274
Ted Kremenekbaa40062010-07-19 22:01:06 +00002275 if (FS.consumesDataArgument()) {
2276 if (atFirstArg) {
2277 atFirstArg = false;
2278 usesPositionalArgs = FS.usesPositionalArg();
2279 }
2280 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002281 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2282 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002283 return false;
2284 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002285 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002286
Ted Kremenekefaff192010-02-27 01:41:03 +00002287 // First check if the field width, precision, and conversion specifier
2288 // have matching data arguments.
2289 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2290 startSpecifier, specifierLen)) {
2291 return false;
2292 }
2293
2294 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2295 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002296 return false;
2297 }
2298
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002299 if (!CS.consumesDataArgument()) {
2300 // FIXME: Technically specifying a precision or field width here
2301 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002302 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002303 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002304
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002305 // Consume the argument.
2306 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002307 if (argIndex < NumDataArgs) {
2308 // The check to see if the argIndex is valid will come later.
2309 // We set the bit here because we may exit early from this
2310 // function if we encounter some other error.
2311 CoveredArgs.set(argIndex);
2312 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002313
2314 // Check for using an Objective-C specific conversion specifier
2315 // in a non-ObjC literal.
2316 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002317 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2318 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002319 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002320
Tom Caree4ee9662010-06-17 19:00:27 +00002321 // Check for invalid use of field width
2322 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002323 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002324 startSpecifier, specifierLen);
2325 }
2326
2327 // Check for invalid use of precision
2328 if (!FS.hasValidPrecision()) {
2329 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2330 startSpecifier, specifierLen);
2331 }
2332
2333 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002334 if (!FS.hasValidThousandsGroupingPrefix())
2335 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002336 if (!FS.hasValidLeadingZeros())
2337 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2338 if (!FS.hasValidPlusPrefix())
2339 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002340 if (!FS.hasValidSpacePrefix())
2341 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002342 if (!FS.hasValidAlternativeForm())
2343 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2344 if (!FS.hasValidLeftJustified())
2345 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2346
2347 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002348 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2349 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2350 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002351 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2352 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2353 startSpecifier, specifierLen);
2354
2355 // Check the length modifier is valid with the given conversion specifier.
2356 const LengthModifier &LM = FS.getLengthModifier();
2357 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002358 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2359 << LM.toString() << CS.toString(),
2360 getLocationOfByte(LM.getStart()),
2361 /*IsStringLocation*/true,
2362 getSpecifierRange(startSpecifier, specifierLen),
2363 FixItHint::CreateRemoval(
2364 getSpecifierRange(LM.getStart(),
2365 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002366 if (!FS.hasStandardLengthModifier())
2367 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002368 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002369 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2370 if (!FS.hasStandardLengthConversionCombination())
2371 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2372 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002373
2374 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002375 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002376 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002377 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2378 getLocationOfByte(CS.getStart()),
2379 /*IsStringLocation*/true,
2380 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002381 // Continue checking the other format specifiers.
2382 return true;
2383 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002384
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002385 // The remaining checks depend on the data arguments.
2386 if (HasVAListArg)
2387 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002388
Ted Kremenek666a1972010-07-26 19:45:42 +00002389 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002390 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002391
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002392 // Now type check the data expression that matches the
2393 // format specifier.
2394 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002395 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2396 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002397 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2398 // Check if we didn't match because of an implicit cast from a 'char'
2399 // or 'short' to an 'int'. This is done because printf is a varargs
2400 // function.
2401 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
James Molloy392da482012-05-04 10:55:22 +00002402 if (ICE->getType() == S.Context.IntTy ||
2403 ICE->getType() == S.Context.UnsignedIntTy) {
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002404 // All further checking is done on the subexpression.
2405 Ex = ICE->getSubExpr();
2406 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002407 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002408 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002409
2410 // We may be able to offer a FixItHint if it is a supported type.
2411 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002412 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002413 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002414
2415 if (success) {
2416 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002417 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002418 llvm::raw_svector_ostream os(buf);
2419 fixedFS.toString(os);
2420
Richard Trieu55733de2011-10-28 00:41:25 +00002421 EmitFormatDiagnostic(
2422 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002423 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002424 << Ex->getSourceRange(),
2425 getLocationOfByte(CS.getStart()),
2426 /*IsStringLocation*/true,
2427 getSpecifierRange(startSpecifier, specifierLen),
2428 FixItHint::CreateReplacement(
2429 getSpecifierRange(startSpecifier, specifierLen),
2430 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002431 }
2432 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002433 EmitFormatDiagnostic(
2434 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2435 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2436 << getSpecifierRange(startSpecifier, specifierLen)
2437 << Ex->getSourceRange(),
2438 getLocationOfByte(CS.getStart()),
2439 true,
2440 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002441 }
2442 }
2443
Ted Kremeneke0e53132010-01-28 23:39:18 +00002444 return true;
2445}
2446
Ted Kremenek826a3452010-07-16 02:11:22 +00002447//===--- CHECK: Scanf format string checking ------------------------------===//
2448
2449namespace {
2450class CheckScanfHandler : public CheckFormatHandler {
2451public:
2452 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2453 const Expr *origFormatExpr, unsigned firstDataArg,
2454 unsigned numDataArgs, bool isObjCLiteral,
2455 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002456 Expr **Args, unsigned NumArgs,
2457 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002458 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2459 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002460 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002461
2462 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2463 const char *startSpecifier,
2464 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002465
2466 bool HandleInvalidScanfConversionSpecifier(
2467 const analyze_scanf::ScanfSpecifier &FS,
2468 const char *startSpecifier,
2469 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002470
2471 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002472};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002473}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002474
Ted Kremenekb7c21012010-07-16 18:28:03 +00002475void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2476 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002477 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2478 getLocationOfByte(end), /*IsStringLocation*/true,
2479 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002480}
2481
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002482bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2483 const analyze_scanf::ScanfSpecifier &FS,
2484 const char *startSpecifier,
2485 unsigned specifierLen) {
2486
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002487 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002488 FS.getConversionSpecifier();
2489
2490 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2491 getLocationOfByte(CS.getStart()),
2492 startSpecifier, specifierLen,
2493 CS.getStart(), CS.getLength());
2494}
2495
Ted Kremenek826a3452010-07-16 02:11:22 +00002496bool CheckScanfHandler::HandleScanfSpecifier(
2497 const analyze_scanf::ScanfSpecifier &FS,
2498 const char *startSpecifier,
2499 unsigned specifierLen) {
2500
2501 using namespace analyze_scanf;
2502 using namespace analyze_format_string;
2503
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002504 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002505
Ted Kremenekbaa40062010-07-19 22:01:06 +00002506 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2507 // be used to decide if we are using positional arguments consistently.
2508 if (FS.consumesDataArgument()) {
2509 if (atFirstArg) {
2510 atFirstArg = false;
2511 usesPositionalArgs = FS.usesPositionalArg();
2512 }
2513 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002514 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2515 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002516 return false;
2517 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002518 }
2519
2520 // Check if the field with is non-zero.
2521 const OptionalAmount &Amt = FS.getFieldWidth();
2522 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2523 if (Amt.getConstantAmount() == 0) {
2524 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2525 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002526 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2527 getLocationOfByte(Amt.getStart()),
2528 /*IsStringLocation*/true, R,
2529 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002530 }
2531 }
2532
2533 if (!FS.consumesDataArgument()) {
2534 // FIXME: Technically specifying a precision or field width here
2535 // makes no sense. Worth issuing a warning at some point.
2536 return true;
2537 }
2538
2539 // Consume the argument.
2540 unsigned argIndex = FS.getArgIndex();
2541 if (argIndex < NumDataArgs) {
2542 // The check to see if the argIndex is valid will come later.
2543 // We set the bit here because we may exit early from this
2544 // function if we encounter some other error.
2545 CoveredArgs.set(argIndex);
2546 }
2547
Ted Kremenek1e51c202010-07-20 20:04:47 +00002548 // Check the length modifier is valid with the given conversion specifier.
2549 const LengthModifier &LM = FS.getLengthModifier();
2550 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002551 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2552 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2553 << LM.toString() << CS.toString()
2554 << getSpecifierRange(startSpecifier, specifierLen),
2555 getLocationOfByte(LM.getStart()),
2556 /*IsStringLocation*/true, R,
2557 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002558 }
2559
Hans Wennborg76517422012-02-22 10:17:01 +00002560 if (!FS.hasStandardLengthModifier())
2561 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002562 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002563 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2564 if (!FS.hasStandardLengthConversionCombination())
2565 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2566 specifierLen);
2567
Ted Kremenek826a3452010-07-16 02:11:22 +00002568 // The remaining checks depend on the data arguments.
2569 if (HasVAListArg)
2570 return true;
2571
Ted Kremenek666a1972010-07-26 19:45:42 +00002572 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002573 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002574
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002575 // Check that the argument type matches the format specifier.
2576 const Expr *Ex = getDataArg(argIndex);
2577 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2578 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2579 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002580 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002581 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002582
2583 if (success) {
2584 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002585 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002586 llvm::raw_svector_ostream os(buf);
2587 fixedFS.toString(os);
2588
2589 EmitFormatDiagnostic(
2590 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2591 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2592 << Ex->getSourceRange(),
2593 getLocationOfByte(CS.getStart()),
2594 /*IsStringLocation*/true,
2595 getSpecifierRange(startSpecifier, specifierLen),
2596 FixItHint::CreateReplacement(
2597 getSpecifierRange(startSpecifier, specifierLen),
2598 os.str()));
2599 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002600 EmitFormatDiagnostic(
2601 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002602 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002603 << Ex->getSourceRange(),
2604 getLocationOfByte(CS.getStart()),
2605 /*IsStringLocation*/true,
2606 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002607 }
2608 }
2609
Ted Kremenek826a3452010-07-16 02:11:22 +00002610 return true;
2611}
2612
2613void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002614 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002615 Expr **Args, unsigned NumArgs,
2616 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002617 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002618 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002619
Ted Kremeneke0e53132010-01-28 23:39:18 +00002620 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002621 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002622 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002623 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002624 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2625 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002626 return;
2627 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002628
Ted Kremeneke0e53132010-01-28 23:39:18 +00002629 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002630 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002631 const char *Str = StrRef.data();
2632 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002633 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002634
Ted Kremeneke0e53132010-01-28 23:39:18 +00002635 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002636 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002637 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002638 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002639 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2640 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002641 return;
2642 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002643
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002644 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002645 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002646 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002647 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002648 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002649
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002650 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002651 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002652 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002653 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002654 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002655 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002656 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002657 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002658
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002659 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002660 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002661 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002662 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002663}
2664
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002665//===--- CHECK: Standard memory functions ---------------------------------===//
2666
Douglas Gregor2a053a32011-05-03 20:05:22 +00002667/// \brief Determine whether the given type is a dynamic class type (e.g.,
2668/// whether it has a vtable).
2669static bool isDynamicClassType(QualType T) {
2670 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2671 if (CXXRecordDecl *Definition = Record->getDefinition())
2672 if (Definition->isDynamicClass())
2673 return true;
2674
2675 return false;
2676}
2677
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002678/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002679/// otherwise returns NULL.
2680static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002681 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002682 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2683 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2684 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002685
Chandler Carruth000d4282011-06-16 09:09:40 +00002686 return 0;
2687}
2688
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002689/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002690static QualType getSizeOfArgType(const Expr* E) {
2691 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2692 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2693 if (SizeOf->getKind() == clang::UETT_SizeOf)
2694 return SizeOf->getTypeOfArgument();
2695
2696 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002697}
2698
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002699/// \brief Check for dangerous or invalid arguments to memset().
2700///
Chandler Carruth929f0132011-06-03 06:23:57 +00002701/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002702/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2703/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002704///
2705/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002706void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002707 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002708 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002709 assert(BId != 0);
2710
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002711 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002712 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002713 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002714 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002715 return;
2716
Anna Zaks0a151a12012-01-17 00:37:07 +00002717 unsigned LastArg = (BId == Builtin::BImemset ||
2718 BId == Builtin::BIstrndup ? 1 : 2);
2719 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002720 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002721
2722 // We have special checking when the length is a sizeof expression.
2723 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2724 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2725 llvm::FoldingSetNodeID SizeOfArgID;
2726
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002727 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2728 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002729 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002730
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002731 QualType DestTy = Dest->getType();
2732 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2733 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002734
Chandler Carruth000d4282011-06-16 09:09:40 +00002735 // Never warn about void type pointers. This can be used to suppress
2736 // false positives.
2737 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002738 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002739
Chandler Carruth000d4282011-06-16 09:09:40 +00002740 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2741 // actually comparing the expressions for equality. Because computing the
2742 // expression IDs can be expensive, we only do this if the diagnostic is
2743 // enabled.
2744 if (SizeOfArg &&
2745 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2746 SizeOfArg->getExprLoc())) {
2747 // We only compute IDs for expressions if the warning is enabled, and
2748 // cache the sizeof arg's ID.
2749 if (SizeOfArgID == llvm::FoldingSetNodeID())
2750 SizeOfArg->Profile(SizeOfArgID, Context, true);
2751 llvm::FoldingSetNodeID DestID;
2752 Dest->Profile(DestID, Context, true);
2753 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002754 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2755 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002756 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2757 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2758 if (UnaryOp->getOpcode() == UO_AddrOf)
2759 ActionIdx = 1; // If its an address-of operator, just remove it.
2760 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2761 ActionIdx = 2; // If the pointee's size is sizeof(char),
2762 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002763 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002764 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002765 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2766 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002767 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002768 << Dest->getSourceRange()
2769 << SizeOfArg->getSourceRange());
2770 break;
2771 }
2772 }
2773
2774 // Also check for cases where the sizeof argument is the exact same
2775 // type as the memory argument, and where it points to a user-defined
2776 // record type.
2777 if (SizeOfArgTy != QualType()) {
2778 if (PointeeTy->isRecordType() &&
2779 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2780 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2781 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2782 << FnName << SizeOfArgTy << ArgIdx
2783 << PointeeTy << Dest->getSourceRange()
2784 << LenExpr->getSourceRange());
2785 break;
2786 }
Nico Webere4a1c642011-06-14 16:14:58 +00002787 }
2788
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002789 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002790 if (isDynamicClassType(PointeeTy)) {
2791
2792 unsigned OperationType = 0;
2793 // "overwritten" if we're warning about the destination for any call
2794 // but memcmp; otherwise a verb appropriate to the call.
2795 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2796 if (BId == Builtin::BImemcpy)
2797 OperationType = 1;
2798 else if(BId == Builtin::BImemmove)
2799 OperationType = 2;
2800 else if (BId == Builtin::BImemcmp)
2801 OperationType = 3;
2802 }
2803
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002804 DiagRuntimeBehavior(
2805 Dest->getExprLoc(), Dest,
2806 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002807 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002808 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002809 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002810 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002811 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2812 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002813 DiagRuntimeBehavior(
2814 Dest->getExprLoc(), Dest,
2815 PDiag(diag::warn_arc_object_memaccess)
2816 << ArgIdx << FnName << PointeeTy
2817 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002818 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002819 continue;
John McCallf85e1932011-06-15 23:02:42 +00002820
2821 DiagRuntimeBehavior(
2822 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002823 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002824 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2825 break;
2826 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002827 }
2828}
2829
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002830// A little helper routine: ignore addition and subtraction of integer literals.
2831// This intentionally does not ignore all integer constant expressions because
2832// we don't want to remove sizeof().
2833static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2834 Ex = Ex->IgnoreParenCasts();
2835
2836 for (;;) {
2837 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2838 if (!BO || !BO->isAdditiveOp())
2839 break;
2840
2841 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2842 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2843
2844 if (isa<IntegerLiteral>(RHS))
2845 Ex = LHS;
2846 else if (isa<IntegerLiteral>(LHS))
2847 Ex = RHS;
2848 else
2849 break;
2850 }
2851
2852 return Ex;
2853}
2854
2855// Warn if the user has made the 'size' argument to strlcpy or strlcat
2856// be the size of the source, instead of the destination.
2857void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2858 IdentifierInfo *FnName) {
2859
2860 // Don't crash if the user has the wrong number of arguments
2861 if (Call->getNumArgs() != 3)
2862 return;
2863
2864 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2865 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2866 const Expr *CompareWithSrc = NULL;
2867
2868 // Look for 'strlcpy(dst, x, sizeof(x))'
2869 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2870 CompareWithSrc = Ex;
2871 else {
2872 // Look for 'strlcpy(dst, x, strlen(x))'
2873 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002874 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002875 && SizeCall->getNumArgs() == 1)
2876 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2877 }
2878 }
2879
2880 if (!CompareWithSrc)
2881 return;
2882
2883 // Determine if the argument to sizeof/strlen is equal to the source
2884 // argument. In principle there's all kinds of things you could do
2885 // here, for instance creating an == expression and evaluating it with
2886 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2887 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2888 if (!SrcArgDRE)
2889 return;
2890
2891 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2892 if (!CompareWithSrcDRE ||
2893 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2894 return;
2895
2896 const Expr *OriginalSizeArg = Call->getArg(2);
2897 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2898 << OriginalSizeArg->getSourceRange() << FnName;
2899
2900 // Output a FIXIT hint if the destination is an array (rather than a
2901 // pointer to an array). This could be enhanced to handle some
2902 // pointers if we know the actual size, like if DstArg is 'array+2'
2903 // we could say 'sizeof(array)-2'.
2904 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002905 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002906
Ted Kremenek8f746222011-08-18 22:48:41 +00002907 // Only handle constant-sized or VLAs, but not flexible members.
2908 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2909 // Only issue the FIXIT for arrays of size > 1.
2910 if (CAT->getSize().getSExtValue() <= 1)
2911 return;
2912 } else if (!DstArgTy->isVariableArrayType()) {
2913 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002914 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002915
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002916 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002917 llvm::raw_svector_ostream OS(sizeString);
2918 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002919 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002920 OS << ")";
2921
2922 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2923 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2924 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002925}
2926
Anna Zaksc36bedc2012-02-01 19:08:57 +00002927/// Check if two expressions refer to the same declaration.
2928static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2929 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2930 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2931 return D1->getDecl() == D2->getDecl();
2932 return false;
2933}
2934
2935static const Expr *getStrlenExprArg(const Expr *E) {
2936 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2937 const FunctionDecl *FD = CE->getDirectCallee();
2938 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2939 return 0;
2940 return CE->getArg(0)->IgnoreParenCasts();
2941 }
2942 return 0;
2943}
2944
2945// Warn on anti-patterns as the 'size' argument to strncat.
2946// The correct size argument should look like following:
2947// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2948void Sema::CheckStrncatArguments(const CallExpr *CE,
2949 IdentifierInfo *FnName) {
2950 // Don't crash if the user has the wrong number of arguments.
2951 if (CE->getNumArgs() < 3)
2952 return;
2953 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2954 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2955 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2956
2957 // Identify common expressions, which are wrongly used as the size argument
2958 // to strncat and may lead to buffer overflows.
2959 unsigned PatternType = 0;
2960 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2961 // - sizeof(dst)
2962 if (referToTheSameDecl(SizeOfArg, DstArg))
2963 PatternType = 1;
2964 // - sizeof(src)
2965 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2966 PatternType = 2;
2967 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2968 if (BE->getOpcode() == BO_Sub) {
2969 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2970 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2971 // - sizeof(dst) - strlen(dst)
2972 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2973 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2974 PatternType = 1;
2975 // - sizeof(src) - (anything)
2976 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2977 PatternType = 2;
2978 }
2979 }
2980
2981 if (PatternType == 0)
2982 return;
2983
Anna Zaksafdb0412012-02-03 01:27:37 +00002984 // Generate the diagnostic.
2985 SourceLocation SL = LenArg->getLocStart();
2986 SourceRange SR = LenArg->getSourceRange();
2987 SourceManager &SM = PP.getSourceManager();
2988
2989 // If the function is defined as a builtin macro, do not show macro expansion.
2990 if (SM.isMacroArgExpansion(SL)) {
2991 SL = SM.getSpellingLoc(SL);
2992 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2993 SM.getSpellingLoc(SR.getEnd()));
2994 }
2995
Anna Zaksc36bedc2012-02-01 19:08:57 +00002996 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002997 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002998 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002999 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003000
3001 // Output a FIXIT hint if the destination is an array (rather than a
3002 // pointer to an array). This could be enhanced to handle some
3003 // pointers if we know the actual size, like if DstArg is 'array+2'
3004 // we could say 'sizeof(array)-2'.
3005 QualType DstArgTy = DstArg->getType();
3006
3007 // Only handle constant-sized or VLAs, but not flexible members.
3008 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3009 // Only issue the FIXIT for arrays of size > 1.
3010 if (CAT->getSize().getSExtValue() <= 1)
3011 return;
3012 } else if (!DstArgTy->isVariableArrayType()) {
3013 return;
3014 }
3015
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003016 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003017 llvm::raw_svector_ostream OS(sizeString);
3018 OS << "sizeof(";
3019 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3020 OS << ") - ";
3021 OS << "strlen(";
3022 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3023 OS << ") - 1";
3024
Anna Zaksafdb0412012-02-03 01:27:37 +00003025 Diag(SL, diag::note_strncat_wrong_size)
3026 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003027}
3028
Ted Kremenek06de2762007-08-17 16:46:58 +00003029//===--- CHECK: Return Address of Stack Variable --------------------------===//
3030
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003031static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3032 Decl *ParentDecl);
3033static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3034 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003035
3036/// CheckReturnStackAddr - Check if a return statement returns the address
3037/// of a stack variable.
3038void
3039Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3040 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003042 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003043 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003044
3045 // Perform checking for returned stack addresses, local blocks,
3046 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003047 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003048 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003049 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003050 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003051 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003052 }
3053
3054 if (stackE == 0)
3055 return; // Nothing suspicious was found.
3056
3057 SourceLocation diagLoc;
3058 SourceRange diagRange;
3059 if (refVars.empty()) {
3060 diagLoc = stackE->getLocStart();
3061 diagRange = stackE->getSourceRange();
3062 } else {
3063 // We followed through a reference variable. 'stackE' contains the
3064 // problematic expression but we will warn at the return statement pointing
3065 // at the reference variable. We will later display the "trail" of
3066 // reference variables using notes.
3067 diagLoc = refVars[0]->getLocStart();
3068 diagRange = refVars[0]->getSourceRange();
3069 }
3070
3071 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3072 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3073 : diag::warn_ret_stack_addr)
3074 << DR->getDecl()->getDeclName() << diagRange;
3075 } else if (isa<BlockExpr>(stackE)) { // local block.
3076 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3077 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3078 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3079 } else { // local temporary.
3080 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3081 : diag::warn_ret_local_temp_addr)
3082 << diagRange;
3083 }
3084
3085 // Display the "trail" of reference variables that we followed until we
3086 // found the problematic expression using notes.
3087 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3088 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3089 // If this var binds to another reference var, show the range of the next
3090 // var, otherwise the var binds to the problematic expression, in which case
3091 // show the range of the expression.
3092 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3093 : stackE->getSourceRange();
3094 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3095 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003096 }
3097}
3098
3099/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3100/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003101/// to a location on the stack, a local block, an address of a label, or a
3102/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003103/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003104/// encounter a subexpression that (1) clearly does not lead to one of the
3105/// above problematic expressions (2) is something we cannot determine leads to
3106/// a problematic expression based on such local checking.
3107///
3108/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3109/// the expression that they point to. Such variables are added to the
3110/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003111///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003112/// EvalAddr processes expressions that are pointers that are used as
3113/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003114/// At the base case of the recursion is a check for the above problematic
3115/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003116///
3117/// This implementation handles:
3118///
3119/// * pointer-to-pointer casts
3120/// * implicit conversions from array references to pointers
3121/// * taking the address of fields
3122/// * arbitrary interplay between "&" and "*" operators
3123/// * pointer arithmetic from an address of a stack variable
3124/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003125static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3126 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003127 if (E->isTypeDependent())
3128 return NULL;
3129
Ted Kremenek06de2762007-08-17 16:46:58 +00003130 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003131 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003132 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003133 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003134 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Peter Collingbournef111d932011-04-15 00:35:48 +00003136 E = E->IgnoreParens();
3137
Ted Kremenek06de2762007-08-17 16:46:58 +00003138 // Our "symbolic interpreter" is just a dispatch off the currently
3139 // viewed AST node. We then recursively traverse the AST by calling
3140 // EvalAddr and EvalVal appropriately.
3141 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003142 case Stmt::DeclRefExprClass: {
3143 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3144
3145 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3146 // If this is a reference variable, follow through to the expression that
3147 // it points to.
3148 if (V->hasLocalStorage() &&
3149 V->getType()->isReferenceType() && V->hasInit()) {
3150 // Add the reference variable to the "trail".
3151 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003152 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003153 }
3154
3155 return NULL;
3156 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003157
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003158 case Stmt::UnaryOperatorClass: {
3159 // The only unary operator that make sense to handle here
3160 // is AddrOf. All others don't make sense as pointers.
3161 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003162
John McCall2de56d12010-08-25 11:45:40 +00003163 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003164 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003165 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003166 return NULL;
3167 }
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003169 case Stmt::BinaryOperatorClass: {
3170 // Handle pointer arithmetic. All other binary operators are not valid
3171 // in this context.
3172 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003173 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003174
John McCall2de56d12010-08-25 11:45:40 +00003175 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003176 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003178 Expr *Base = B->getLHS();
3179
3180 // Determine which argument is the real pointer base. It could be
3181 // the RHS argument instead of the LHS.
3182 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003184 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003185 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003186 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003187
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003188 // For conditional operators we need to see if either the LHS or RHS are
3189 // valid DeclRefExpr*s. If one of them is valid, we return it.
3190 case Stmt::ConditionalOperatorClass: {
3191 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003193 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003194 if (Expr *lhsExpr = C->getLHS()) {
3195 // In C++, we can have a throw-expression, which has 'void' type.
3196 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003197 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003198 return LHS;
3199 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003200
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003201 // In C++, we can have a throw-expression, which has 'void' type.
3202 if (C->getRHS()->getType()->isVoidType())
3203 return NULL;
3204
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003205 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003206 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003207
3208 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003209 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003210 return E; // local block.
3211 return NULL;
3212
3213 case Stmt::AddrLabelExprClass:
3214 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003215
John McCall80ee6e82011-11-10 05:35:25 +00003216 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003217 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3218 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003219
Ted Kremenek54b52742008-08-07 00:49:01 +00003220 // For casts, we need to handle conversions from arrays to
3221 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003222 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003223 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003224 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003225 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003226 case Stmt::CXXStaticCastExprClass:
3227 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003228 case Stmt::CXXConstCastExprClass:
3229 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003230 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3231 switch (cast<CastExpr>(E)->getCastKind()) {
3232 case CK_BitCast:
3233 case CK_LValueToRValue:
3234 case CK_NoOp:
3235 case CK_BaseToDerived:
3236 case CK_DerivedToBase:
3237 case CK_UncheckedDerivedToBase:
3238 case CK_Dynamic:
3239 case CK_CPointerToObjCPointerCast:
3240 case CK_BlockPointerToObjCPointerCast:
3241 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003242 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003243
3244 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003245 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003246
3247 default:
3248 return 0;
3249 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003250 }
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Douglas Gregor03e80032011-06-21 17:03:29 +00003252 case Stmt::MaterializeTemporaryExprClass:
3253 if (Expr *Result = EvalAddr(
3254 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003255 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003256 return Result;
3257
3258 return E;
3259
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003260 // Everything else: we simply don't reason about them.
3261 default:
3262 return NULL;
3263 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003264}
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Ted Kremenek06de2762007-08-17 16:46:58 +00003266
3267/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3268/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003269static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3270 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003271do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003272 // We should only be called for evaluating non-pointer expressions, or
3273 // expressions with a pointer type that are not used as references but instead
3274 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Ted Kremenek06de2762007-08-17 16:46:58 +00003276 // Our "symbolic interpreter" is just a dispatch off the currently
3277 // viewed AST node. We then recursively traverse the AST by calling
3278 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003279
3280 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003281 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003282 case Stmt::ImplicitCastExprClass: {
3283 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003284 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003285 E = IE->getSubExpr();
3286 continue;
3287 }
3288 return NULL;
3289 }
3290
John McCall80ee6e82011-11-10 05:35:25 +00003291 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003292 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003293
Douglas Gregora2813ce2009-10-23 18:54:35 +00003294 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003295 // When we hit a DeclRefExpr we are looking at code that refers to a
3296 // variable's name. If it's not a reference variable we check if it has
3297 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003298 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003300 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3301 // Check if it refers to itself, e.g. "int& i = i;".
3302 if (V == ParentDecl)
3303 return DR;
3304
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003305 if (V->hasLocalStorage()) {
3306 if (!V->getType()->isReferenceType())
3307 return DR;
3308
3309 // Reference variable, follow through to the expression that
3310 // it points to.
3311 if (V->hasInit()) {
3312 // Add the reference variable to the "trail".
3313 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003314 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003315 }
3316 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003317 }
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Ted Kremenek06de2762007-08-17 16:46:58 +00003319 return NULL;
3320 }
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Ted Kremenek06de2762007-08-17 16:46:58 +00003322 case Stmt::UnaryOperatorClass: {
3323 // The only unary operator that make sense to handle here
3324 // is Deref. All others don't resolve to a "name." This includes
3325 // handling all sorts of rvalues passed to a unary operator.
3326 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003327
John McCall2de56d12010-08-25 11:45:40 +00003328 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003329 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003330
3331 return NULL;
3332 }
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Ted Kremenek06de2762007-08-17 16:46:58 +00003334 case Stmt::ArraySubscriptExprClass: {
3335 // Array subscripts are potential references to data on the stack. We
3336 // retrieve the DeclRefExpr* for the array variable if it indeed
3337 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003338 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003339 }
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Ted Kremenek06de2762007-08-17 16:46:58 +00003341 case Stmt::ConditionalOperatorClass: {
3342 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003343 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003344 ConditionalOperator *C = cast<ConditionalOperator>(E);
3345
Anders Carlsson39073232007-11-30 19:04:31 +00003346 // Handle the GNU extension for missing LHS.
3347 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003348 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003349 return LHS;
3350
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003351 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003352 }
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Ted Kremenek06de2762007-08-17 16:46:58 +00003354 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003355 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003356 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Ted Kremenek06de2762007-08-17 16:46:58 +00003358 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003359 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003360 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003361
3362 // Check whether the member type is itself a reference, in which case
3363 // we're not going to refer to the member, but to what the member refers to.
3364 if (M->getMemberDecl()->getType()->isReferenceType())
3365 return NULL;
3366
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003367 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003368 }
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Douglas Gregor03e80032011-06-21 17:03:29 +00003370 case Stmt::MaterializeTemporaryExprClass:
3371 if (Expr *Result = EvalVal(
3372 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003373 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003374 return Result;
3375
3376 return E;
3377
Ted Kremenek06de2762007-08-17 16:46:58 +00003378 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003379 // Check that we don't return or take the address of a reference to a
3380 // temporary. This is only useful in C++.
3381 if (!E->isTypeDependent() && E->isRValue())
3382 return E;
3383
3384 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003385 return NULL;
3386 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003387} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003388}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003389
3390//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3391
3392/// Check for comparisons of floating point operands using != and ==.
3393/// Issue a warning if these are no self-comparisons, as they are not likely
3394/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003395void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003396 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Richard Trieudd225092011-09-15 21:56:47 +00003398 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3399 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003400
3401 // Special case: check for x == x (which is OK).
3402 // Do not emit warnings for such cases.
3403 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3404 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3405 if (DRL->getDecl() == DRR->getDecl())
3406 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003407
3408
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003409 // Special case: check for comparisons against literals that can be exactly
3410 // represented by APFloat. In such cases, do not emit a warning. This
3411 // is a heuristic: often comparison against such literals are used to
3412 // detect if a value in a variable has not changed. This clearly can
3413 // lead to false negatives.
3414 if (EmitWarning) {
3415 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3416 if (FLL->isExact())
3417 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003418 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003419 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3420 if (FLR->isExact())
3421 EmitWarning = false;
3422 }
3423 }
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003425 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003426 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003427 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003428 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003429 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Sebastian Redl0eb23302009-01-19 00:08:26 +00003431 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003432 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003433 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003434 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003436 // Emit the diagnostic.
3437 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003438 Diag(Loc, diag::warn_floatingpoint_eq)
3439 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003440}
John McCallba26e582010-01-04 23:21:16 +00003441
John McCallf2370c92010-01-06 05:24:50 +00003442//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3443//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003444
John McCallf2370c92010-01-06 05:24:50 +00003445namespace {
John McCallba26e582010-01-04 23:21:16 +00003446
John McCallf2370c92010-01-06 05:24:50 +00003447/// Structure recording the 'active' range of an integer-valued
3448/// expression.
3449struct IntRange {
3450 /// The number of bits active in the int.
3451 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003452
John McCallf2370c92010-01-06 05:24:50 +00003453 /// True if the int is known not to have negative values.
3454 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003455
John McCallf2370c92010-01-06 05:24:50 +00003456 IntRange(unsigned Width, bool NonNegative)
3457 : Width(Width), NonNegative(NonNegative)
3458 {}
John McCallba26e582010-01-04 23:21:16 +00003459
John McCall1844a6e2010-11-10 23:38:19 +00003460 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003461 static IntRange forBoolType() {
3462 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003463 }
3464
John McCall1844a6e2010-11-10 23:38:19 +00003465 /// Returns the range of an opaque value of the given integral type.
3466 static IntRange forValueOfType(ASTContext &C, QualType T) {
3467 return forValueOfCanonicalType(C,
3468 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003469 }
3470
John McCall1844a6e2010-11-10 23:38:19 +00003471 /// Returns the range of an opaque value of a canonical integral type.
3472 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003473 assert(T->isCanonicalUnqualified());
3474
3475 if (const VectorType *VT = dyn_cast<VectorType>(T))
3476 T = VT->getElementType().getTypePtr();
3477 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3478 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003479
John McCall091f23f2010-11-09 22:22:12 +00003480 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003481 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3482 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003483 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003484 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3485
John McCall323ed742010-05-06 08:58:33 +00003486 unsigned NumPositive = Enum->getNumPositiveBits();
3487 unsigned NumNegative = Enum->getNumNegativeBits();
3488
3489 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3490 }
John McCallf2370c92010-01-06 05:24:50 +00003491
3492 const BuiltinType *BT = cast<BuiltinType>(T);
3493 assert(BT->isInteger());
3494
3495 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3496 }
3497
John McCall1844a6e2010-11-10 23:38:19 +00003498 /// Returns the "target" range of a canonical integral type, i.e.
3499 /// the range of values expressible in the type.
3500 ///
3501 /// This matches forValueOfCanonicalType except that enums have the
3502 /// full range of their type, not the range of their enumerators.
3503 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3504 assert(T->isCanonicalUnqualified());
3505
3506 if (const VectorType *VT = dyn_cast<VectorType>(T))
3507 T = VT->getElementType().getTypePtr();
3508 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3509 T = CT->getElementType().getTypePtr();
3510 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003511 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003512
3513 const BuiltinType *BT = cast<BuiltinType>(T);
3514 assert(BT->isInteger());
3515
3516 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3517 }
3518
3519 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003520 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003521 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003522 L.NonNegative && R.NonNegative);
3523 }
3524
John McCall1844a6e2010-11-10 23:38:19 +00003525 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003526 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003527 return IntRange(std::min(L.Width, R.Width),
3528 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003529 }
3530};
3531
Ted Kremenek0692a192012-01-31 05:37:37 +00003532static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3533 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003534 if (value.isSigned() && value.isNegative())
3535 return IntRange(value.getMinSignedBits(), false);
3536
3537 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003538 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003539
3540 // isNonNegative() just checks the sign bit without considering
3541 // signedness.
3542 return IntRange(value.getActiveBits(), true);
3543}
3544
Ted Kremenek0692a192012-01-31 05:37:37 +00003545static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3546 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003547 if (result.isInt())
3548 return GetValueRange(C, result.getInt(), MaxWidth);
3549
3550 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003551 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3552 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3553 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3554 R = IntRange::join(R, El);
3555 }
John McCallf2370c92010-01-06 05:24:50 +00003556 return R;
3557 }
3558
3559 if (result.isComplexInt()) {
3560 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3561 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3562 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003563 }
3564
3565 // This can happen with lossless casts to intptr_t of "based" lvalues.
3566 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003567 // FIXME: The only reason we need to pass the type in here is to get
3568 // the sign right on this one case. It would be nice if APValue
3569 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003570 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003571 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003572}
John McCallf2370c92010-01-06 05:24:50 +00003573
3574/// Pseudo-evaluate the given integer expression, estimating the
3575/// range of values it might take.
3576///
3577/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003578static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003579 E = E->IgnoreParens();
3580
3581 // Try a full evaluation first.
3582 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003583 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003584 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003585
3586 // I think we only want to look through implicit casts here; if the
3587 // user has an explicit widening cast, we should treat the value as
3588 // being of the new, wider type.
3589 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003590 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003591 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3592
John McCall1844a6e2010-11-10 23:38:19 +00003593 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003594
John McCall2de56d12010-08-25 11:45:40 +00003595 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003596
John McCallf2370c92010-01-06 05:24:50 +00003597 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003598 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003599 return OutputTypeRange;
3600
3601 IntRange SubRange
3602 = GetExprRange(C, CE->getSubExpr(),
3603 std::min(MaxWidth, OutputTypeRange.Width));
3604
3605 // Bail out if the subexpr's range is as wide as the cast type.
3606 if (SubRange.Width >= OutputTypeRange.Width)
3607 return OutputTypeRange;
3608
3609 // Otherwise, we take the smaller width, and we're non-negative if
3610 // either the output type or the subexpr is.
3611 return IntRange(SubRange.Width,
3612 SubRange.NonNegative || OutputTypeRange.NonNegative);
3613 }
3614
3615 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3616 // If we can fold the condition, just take that operand.
3617 bool CondResult;
3618 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3619 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3620 : CO->getFalseExpr(),
3621 MaxWidth);
3622
3623 // Otherwise, conservatively merge.
3624 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3625 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3626 return IntRange::join(L, R);
3627 }
3628
3629 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3630 switch (BO->getOpcode()) {
3631
3632 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003633 case BO_LAnd:
3634 case BO_LOr:
3635 case BO_LT:
3636 case BO_GT:
3637 case BO_LE:
3638 case BO_GE:
3639 case BO_EQ:
3640 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003641 return IntRange::forBoolType();
3642
John McCall862ff872011-07-13 06:35:24 +00003643 // The type of the assignments is the type of the LHS, so the RHS
3644 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003645 case BO_MulAssign:
3646 case BO_DivAssign:
3647 case BO_RemAssign:
3648 case BO_AddAssign:
3649 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003650 case BO_XorAssign:
3651 case BO_OrAssign:
3652 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003653 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003654
John McCall862ff872011-07-13 06:35:24 +00003655 // Simple assignments just pass through the RHS, which will have
3656 // been coerced to the LHS type.
3657 case BO_Assign:
3658 // TODO: bitfields?
3659 return GetExprRange(C, BO->getRHS(), MaxWidth);
3660
John McCallf2370c92010-01-06 05:24:50 +00003661 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003662 case BO_PtrMemD:
3663 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003664 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003665
John McCall60fad452010-01-06 22:07:33 +00003666 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003667 case BO_And:
3668 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003669 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3670 GetExprRange(C, BO->getRHS(), MaxWidth));
3671
John McCallf2370c92010-01-06 05:24:50 +00003672 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003673 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003674 // ...except that we want to treat '1 << (blah)' as logically
3675 // positive. It's an important idiom.
3676 if (IntegerLiteral *I
3677 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3678 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003679 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003680 return IntRange(R.Width, /*NonNegative*/ true);
3681 }
3682 }
3683 // fallthrough
3684
John McCall2de56d12010-08-25 11:45:40 +00003685 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003686 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003687
John McCall60fad452010-01-06 22:07:33 +00003688 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003689 case BO_Shr:
3690 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003691 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3692
3693 // If the shift amount is a positive constant, drop the width by
3694 // that much.
3695 llvm::APSInt shift;
3696 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3697 shift.isNonNegative()) {
3698 unsigned zext = shift.getZExtValue();
3699 if (zext >= L.Width)
3700 L.Width = (L.NonNegative ? 0 : 1);
3701 else
3702 L.Width -= zext;
3703 }
3704
3705 return L;
3706 }
3707
3708 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003709 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003710 return GetExprRange(C, BO->getRHS(), MaxWidth);
3711
John McCall60fad452010-01-06 22:07:33 +00003712 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003713 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003714 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003715 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003716 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003717
John McCall00fe7612011-07-14 22:39:48 +00003718 // The width of a division result is mostly determined by the size
3719 // of the LHS.
3720 case BO_Div: {
3721 // Don't 'pre-truncate' the operands.
3722 unsigned opWidth = C.getIntWidth(E->getType());
3723 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3724
3725 // If the divisor is constant, use that.
3726 llvm::APSInt divisor;
3727 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3728 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3729 if (log2 >= L.Width)
3730 L.Width = (L.NonNegative ? 0 : 1);
3731 else
3732 L.Width = std::min(L.Width - log2, MaxWidth);
3733 return L;
3734 }
3735
3736 // Otherwise, just use the LHS's width.
3737 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3738 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3739 }
3740
3741 // The result of a remainder can't be larger than the result of
3742 // either side.
3743 case BO_Rem: {
3744 // Don't 'pre-truncate' the operands.
3745 unsigned opWidth = C.getIntWidth(E->getType());
3746 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3747 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3748
3749 IntRange meet = IntRange::meet(L, R);
3750 meet.Width = std::min(meet.Width, MaxWidth);
3751 return meet;
3752 }
3753
3754 // The default behavior is okay for these.
3755 case BO_Mul:
3756 case BO_Add:
3757 case BO_Xor:
3758 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003759 break;
3760 }
3761
John McCall00fe7612011-07-14 22:39:48 +00003762 // The default case is to treat the operation as if it were closed
3763 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003764 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3765 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3766 return IntRange::join(L, R);
3767 }
3768
3769 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3770 switch (UO->getOpcode()) {
3771 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003772 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003773 return IntRange::forBoolType();
3774
3775 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003776 case UO_Deref:
3777 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003778 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003779
3780 default:
3781 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3782 }
3783 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003784
3785 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003786 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003787 }
John McCallf2370c92010-01-06 05:24:50 +00003788
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003789 if (FieldDecl *BitField = E->getBitField())
3790 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003791 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003792
John McCall1844a6e2010-11-10 23:38:19 +00003793 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003794}
John McCall51313c32010-01-04 23:31:57 +00003795
Ted Kremenek0692a192012-01-31 05:37:37 +00003796static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003797 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3798}
3799
John McCall51313c32010-01-04 23:31:57 +00003800/// Checks whether the given value, which currently has the given
3801/// source semantics, has the same value when coerced through the
3802/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003803static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3804 const llvm::fltSemantics &Src,
3805 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003806 llvm::APFloat truncated = value;
3807
3808 bool ignored;
3809 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3810 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3811
3812 return truncated.bitwiseIsEqual(value);
3813}
3814
3815/// Checks whether the given value, which currently has the given
3816/// source semantics, has the same value when coerced through the
3817/// target semantics.
3818///
3819/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003820static bool IsSameFloatAfterCast(const APValue &value,
3821 const llvm::fltSemantics &Src,
3822 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003823 if (value.isFloat())
3824 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3825
3826 if (value.isVector()) {
3827 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3828 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3829 return false;
3830 return true;
3831 }
3832
3833 assert(value.isComplexFloat());
3834 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3835 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3836}
3837
Ted Kremenek0692a192012-01-31 05:37:37 +00003838static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003839
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003840static bool IsZero(Sema &S, Expr *E) {
3841 // Suppress cases where we are comparing against an enum constant.
3842 if (const DeclRefExpr *DR =
3843 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3844 if (isa<EnumConstantDecl>(DR->getDecl()))
3845 return false;
3846
3847 // Suppress cases where the '0' value is expanded from a macro.
3848 if (E->getLocStart().isMacroID())
3849 return false;
3850
John McCall323ed742010-05-06 08:58:33 +00003851 llvm::APSInt Value;
3852 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3853}
3854
John McCall372e1032010-10-06 00:25:24 +00003855static bool HasEnumType(Expr *E) {
3856 // Strip off implicit integral promotions.
3857 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003858 if (ICE->getCastKind() != CK_IntegralCast &&
3859 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003860 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003861 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003862 }
3863
3864 return E->getType()->isEnumeralType();
3865}
3866
Ted Kremenek0692a192012-01-31 05:37:37 +00003867static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003868 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003869 if (E->isValueDependent())
3870 return;
3871
John McCall2de56d12010-08-25 11:45:40 +00003872 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003873 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003874 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003875 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003876 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003877 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003878 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003879 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003880 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003881 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003882 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003883 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003884 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003885 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003886 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003887 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3888 }
3889}
3890
3891/// Analyze the operands of the given comparison. Implements the
3892/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003893static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003894 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3895 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003896}
John McCall51313c32010-01-04 23:31:57 +00003897
John McCallba26e582010-01-04 23:21:16 +00003898/// \brief Implements -Wsign-compare.
3899///
Richard Trieudd225092011-09-15 21:56:47 +00003900/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003901static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003902 // The type the comparison is being performed in.
3903 QualType T = E->getLHS()->getType();
3904 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3905 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003906
John McCall323ed742010-05-06 08:58:33 +00003907 // We don't do anything special if this isn't an unsigned integral
3908 // comparison: we're only interested in integral comparisons, and
3909 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003910 //
3911 // We also don't care about value-dependent expressions or expressions
3912 // whose result is a constant.
3913 if (!T->hasUnsignedIntegerRepresentation()
3914 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003915 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003916
Richard Trieudd225092011-09-15 21:56:47 +00003917 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3918 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003919
John McCall323ed742010-05-06 08:58:33 +00003920 // Check to see if one of the (unmodified) operands is of different
3921 // signedness.
3922 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003923 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3924 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003925 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003926 signedOperand = LHS;
3927 unsignedOperand = RHS;
3928 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3929 signedOperand = RHS;
3930 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003931 } else {
John McCall323ed742010-05-06 08:58:33 +00003932 CheckTrivialUnsignedComparison(S, E);
3933 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003934 }
3935
John McCall323ed742010-05-06 08:58:33 +00003936 // Otherwise, calculate the effective range of the signed operand.
3937 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003938
John McCall323ed742010-05-06 08:58:33 +00003939 // Go ahead and analyze implicit conversions in the operands. Note
3940 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003941 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3942 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003943
John McCall323ed742010-05-06 08:58:33 +00003944 // If the signed range is non-negative, -Wsign-compare won't fire,
3945 // but we should still check for comparisons which are always true
3946 // or false.
3947 if (signedRange.NonNegative)
3948 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003949
3950 // For (in)equality comparisons, if the unsigned operand is a
3951 // constant which cannot collide with a overflowed signed operand,
3952 // then reinterpreting the signed operand as unsigned will not
3953 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003954 if (E->isEqualityOp()) {
3955 unsigned comparisonWidth = S.Context.getIntWidth(T);
3956 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003957
John McCall323ed742010-05-06 08:58:33 +00003958 // We should never be unable to prove that the unsigned operand is
3959 // non-negative.
3960 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3961
3962 if (unsignedRange.Width < comparisonWidth)
3963 return;
3964 }
3965
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00003966 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
3967 S.PDiag(diag::warn_mixed_sign_comparison)
3968 << LHS->getType() << RHS->getType()
3969 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00003970}
3971
John McCall15d7d122010-11-11 03:21:53 +00003972/// Analyzes an attempt to assign the given value to a bitfield.
3973///
3974/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003975static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3976 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003977 assert(Bitfield->isBitField());
3978 if (Bitfield->isInvalidDecl())
3979 return false;
3980
John McCall91b60142010-11-11 05:33:51 +00003981 // White-list bool bitfields.
3982 if (Bitfield->getType()->isBooleanType())
3983 return false;
3984
Douglas Gregor46ff3032011-02-04 13:09:01 +00003985 // Ignore value- or type-dependent expressions.
3986 if (Bitfield->getBitWidth()->isValueDependent() ||
3987 Bitfield->getBitWidth()->isTypeDependent() ||
3988 Init->isValueDependent() ||
3989 Init->isTypeDependent())
3990 return false;
3991
John McCall15d7d122010-11-11 03:21:53 +00003992 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3993
Richard Smith80d4b552011-12-28 19:48:30 +00003994 llvm::APSInt Value;
3995 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003996 return false;
3997
John McCall15d7d122010-11-11 03:21:53 +00003998 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003999 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004000
4001 if (OriginalWidth <= FieldWidth)
4002 return false;
4003
Eli Friedman3a643af2012-01-26 23:11:39 +00004004 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004005 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004006 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004007
Eli Friedman3a643af2012-01-26 23:11:39 +00004008 // Check whether the stored value is equal to the original value.
4009 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004010 if (Value == TruncatedValue)
4011 return false;
4012
Eli Friedman3a643af2012-01-26 23:11:39 +00004013 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004014 // therefore don't strictly fit into a signed bitfield of width 1.
4015 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004016 return false;
4017
John McCall15d7d122010-11-11 03:21:53 +00004018 std::string PrettyValue = Value.toString(10);
4019 std::string PrettyTrunc = TruncatedValue.toString(10);
4020
4021 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4022 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4023 << Init->getSourceRange();
4024
4025 return true;
4026}
4027
John McCallbeb22aa2010-11-09 23:24:47 +00004028/// Analyze the given simple or compound assignment for warning-worthy
4029/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004030static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004031 // Just recurse on the LHS.
4032 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4033
4034 // We want to recurse on the RHS as normal unless we're assigning to
4035 // a bitfield.
4036 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004037 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4038 E->getOperatorLoc())) {
4039 // Recurse, ignoring any implicit conversions on the RHS.
4040 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4041 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004042 }
4043 }
4044
4045 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4046}
4047
John McCall51313c32010-01-04 23:31:57 +00004048/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004049static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004050 SourceLocation CContext, unsigned diag,
4051 bool pruneControlFlow = false) {
4052 if (pruneControlFlow) {
4053 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4054 S.PDiag(diag)
4055 << SourceType << T << E->getSourceRange()
4056 << SourceRange(CContext));
4057 return;
4058 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004059 S.Diag(E->getExprLoc(), diag)
4060 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4061}
4062
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004063/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004064static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004065 SourceLocation CContext, unsigned diag,
4066 bool pruneControlFlow = false) {
4067 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004068}
4069
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004070/// Diagnose an implicit cast from a literal expression. Does not warn when the
4071/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004072void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4073 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004074 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004075 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004076 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004077 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4078 T->hasUnsignedIntegerRepresentation());
4079 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004080 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004081 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004082 return;
4083
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004084 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
4085 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004086}
4087
John McCall091f23f2010-11-09 22:22:12 +00004088std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4089 if (!Range.Width) return "0";
4090
4091 llvm::APSInt ValueInRange = Value;
4092 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004093 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004094 return ValueInRange.toString(10);
4095}
4096
John McCall323ed742010-05-06 08:58:33 +00004097void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004098 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004099 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004100
John McCall323ed742010-05-06 08:58:33 +00004101 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4102 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4103 if (Source == Target) return;
4104 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004105
Chandler Carruth108f7562011-07-26 05:40:03 +00004106 // If the conversion context location is invalid don't complain. We also
4107 // don't want to emit a warning if the issue occurs from the expansion of
4108 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4109 // delay this check as long as possible. Once we detect we are in that
4110 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004111 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004112 return;
4113
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004114 // Diagnose implicit casts to bool.
4115 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4116 if (isa<StringLiteral>(E))
4117 // Warn on string literal to bool. Checks for string literals in logical
4118 // expressions, for instances, assert(0 && "error here"), is prevented
4119 // by a check in AnalyzeImplicitConversions().
4120 return DiagnoseImpCast(S, E, T, CC,
4121 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004122 if (Source->isFunctionType()) {
4123 // Warn on function to bool. Checks free functions and static member
4124 // functions. Weakly imported functions are excluded from the check,
4125 // since it's common to test their value to check whether the linker
4126 // found a definition for them.
4127 ValueDecl *D = 0;
4128 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4129 D = R->getDecl();
4130 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4131 D = M->getMemberDecl();
4132 }
4133
4134 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004135 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4136 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4137 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004138 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4139 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4140 QualType ReturnType;
4141 UnresolvedSet<4> NonTemplateOverloads;
4142 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4143 if (!ReturnType.isNull()
4144 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4145 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4146 << FixItHint::CreateInsertion(
4147 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004148 return;
4149 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004150 }
4151 }
David Blaikiee37cdc42011-09-29 04:06:47 +00004152 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004153 }
John McCall51313c32010-01-04 23:31:57 +00004154
4155 // Strip vector types.
4156 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004157 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004158 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004159 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004160 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004161 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004162
4163 // If the vector cast is cast between two vectors of the same size, it is
4164 // a bitcast, not a conversion.
4165 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4166 return;
John McCall51313c32010-01-04 23:31:57 +00004167
4168 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4169 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4170 }
4171
4172 // Strip complex types.
4173 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004174 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004175 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004176 return;
4177
John McCallb4eb64d2010-10-08 02:01:28 +00004178 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004179 }
John McCall51313c32010-01-04 23:31:57 +00004180
4181 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4182 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4183 }
4184
4185 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4186 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4187
4188 // If the source is floating point...
4189 if (SourceBT && SourceBT->isFloatingPoint()) {
4190 // ...and the target is floating point...
4191 if (TargetBT && TargetBT->isFloatingPoint()) {
4192 // ...then warn if we're dropping FP rank.
4193
4194 // Builtin FP kinds are ordered by increasing FP rank.
4195 if (SourceBT->getKind() > TargetBT->getKind()) {
4196 // Don't warn about float constants that are precisely
4197 // representable in the target type.
4198 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004199 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004200 // Value might be a float, a float vector, or a float complex.
4201 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004202 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4203 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004204 return;
4205 }
4206
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004207 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004208 return;
4209
John McCallb4eb64d2010-10-08 02:01:28 +00004210 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004211 }
4212 return;
4213 }
4214
Ted Kremenekef9ff882011-03-10 20:03:42 +00004215 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00004216 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004217 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004218 return;
4219
Chandler Carrutha5b93322011-02-17 11:05:49 +00004220 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004221 // We also want to warn on, e.g., "int i = -1.234"
4222 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4223 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4224 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4225
Chandler Carruthf65076e2011-04-10 08:36:24 +00004226 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4227 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004228 } else {
4229 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4230 }
4231 }
John McCall51313c32010-01-04 23:31:57 +00004232
4233 return;
4234 }
4235
John McCallf2370c92010-01-06 05:24:50 +00004236 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004237 return;
4238
Richard Trieu1838ca52011-05-29 19:59:02 +00004239 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4240 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004241 SourceLocation Loc = E->getSourceRange().getBegin();
4242 if (Loc.isMacroID())
4243 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4244 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
David Blaikie2c0abf42012-04-30 18:27:22 +00004245 << T << clang::SourceRange(CC)
4246 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004247 return;
4248 }
4249
John McCall323ed742010-05-06 08:58:33 +00004250 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004251 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004252
4253 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004254 // If the source is a constant, use a default-on diagnostic.
4255 // TODO: this should happen for bitfield stores, too.
4256 llvm::APSInt Value(32);
4257 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004258 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004259 return;
4260
John McCall091f23f2010-11-09 22:22:12 +00004261 std::string PrettySourceValue = Value.toString(10);
4262 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4263
Ted Kremenek5e745da2011-10-22 02:37:33 +00004264 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4265 S.PDiag(diag::warn_impcast_integer_precision_constant)
4266 << PrettySourceValue << PrettyTargetValue
4267 << E->getType() << T << E->getSourceRange()
4268 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004269 return;
4270 }
4271
Chris Lattnerb792b302011-06-14 04:51:15 +00004272 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004273 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004274 return;
4275
David Blaikie37050842012-04-12 22:40:54 +00004276 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004277 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4278 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004279 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004280 }
4281
4282 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4283 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4284 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004285
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004286 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004287 return;
4288
John McCall323ed742010-05-06 08:58:33 +00004289 unsigned DiagID = diag::warn_impcast_integer_sign;
4290
4291 // Traditionally, gcc has warned about this under -Wsign-compare.
4292 // We also want to warn about it in -Wconversion.
4293 // So if -Wconversion is off, use a completely identical diagnostic
4294 // in the sign-compare group.
4295 // The conditional-checking code will
4296 if (ICContext) {
4297 DiagID = diag::warn_impcast_integer_sign_conditional;
4298 *ICContext = true;
4299 }
4300
John McCallb4eb64d2010-10-08 02:01:28 +00004301 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004302 }
4303
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004304 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004305 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4306 // type, to give us better diagnostics.
4307 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004308 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004309 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4310 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4311 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4312 SourceType = S.Context.getTypeDeclType(Enum);
4313 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4314 }
4315 }
4316
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004317 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4318 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4319 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004320 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004321 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004322 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004323 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004324 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004325 return;
4326
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004327 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004328 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004329 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004330
John McCall51313c32010-01-04 23:31:57 +00004331 return;
4332}
4333
John McCall323ed742010-05-06 08:58:33 +00004334void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4335
4336void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004337 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004338 E = E->IgnoreParenImpCasts();
4339
4340 if (isa<ConditionalOperator>(E))
4341 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4342
John McCallb4eb64d2010-10-08 02:01:28 +00004343 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004344 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004345 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004346 return;
4347}
4348
4349void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004350 SourceLocation CC = E->getQuestionLoc();
4351
4352 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004353
4354 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004355 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4356 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004357
4358 // If -Wconversion would have warned about either of the candidates
4359 // for a signedness conversion to the context type...
4360 if (!Suspicious) return;
4361
4362 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004363 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4364 CC))
John McCall323ed742010-05-06 08:58:33 +00004365 return;
4366
John McCall323ed742010-05-06 08:58:33 +00004367 // ...then check whether it would have warned about either of the
4368 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004369 if (E->getType() == T) return;
4370
4371 Suspicious = false;
4372 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4373 E->getType(), CC, &Suspicious);
4374 if (!Suspicious)
4375 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004376 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004377}
4378
4379/// AnalyzeImplicitConversions - Find and report any interesting
4380/// implicit conversions in the given expression. There are a couple
4381/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004382void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004383 QualType T = OrigE->getType();
4384 Expr *E = OrigE->IgnoreParenImpCasts();
4385
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004386 if (E->isTypeDependent() || E->isValueDependent())
4387 return;
4388
John McCall323ed742010-05-06 08:58:33 +00004389 // For conditional operators, we analyze the arguments as if they
4390 // were being fed directly into the output.
4391 if (isa<ConditionalOperator>(E)) {
4392 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4393 CheckConditionalOperator(S, CO, T);
4394 return;
4395 }
4396
4397 // Go ahead and check any implicit conversions we might have skipped.
4398 // The non-canonical typecheck is just an optimization;
4399 // CheckImplicitConversion will filter out dead implicit conversions.
4400 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004401 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004402
4403 // Now continue drilling into this expression.
4404
4405 // Skip past explicit casts.
4406 if (isa<ExplicitCastExpr>(E)) {
4407 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004408 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004409 }
4410
John McCallbeb22aa2010-11-09 23:24:47 +00004411 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4412 // Do a somewhat different check with comparison operators.
4413 if (BO->isComparisonOp())
4414 return AnalyzeComparison(S, BO);
4415
Eli Friedman0fa06382012-01-26 23:34:06 +00004416 // And with simple assignments.
4417 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004418 return AnalyzeAssignment(S, BO);
4419 }
John McCall323ed742010-05-06 08:58:33 +00004420
4421 // These break the otherwise-useful invariant below. Fortunately,
4422 // we don't really need to recurse into them, because any internal
4423 // expressions should have been analyzed already when they were
4424 // built into statements.
4425 if (isa<StmtExpr>(E)) return;
4426
4427 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004428 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004429
4430 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004431 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004432 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4433 bool IsLogicalOperator = BO && BO->isLogicalOp();
4434 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004435 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004436 if (!ChildExpr)
4437 continue;
4438
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004439 if (IsLogicalOperator &&
4440 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4441 // Ignore checking string literals that are in logical operators.
4442 continue;
4443 AnalyzeImplicitConversions(S, ChildExpr, CC);
4444 }
John McCall323ed742010-05-06 08:58:33 +00004445}
4446
4447} // end anonymous namespace
4448
4449/// Diagnoses "dangerous" implicit conversions within the given
4450/// expression (which is a full expression). Implements -Wconversion
4451/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004452///
4453/// \param CC the "context" location of the implicit conversion, i.e.
4454/// the most location of the syntactic entity requiring the implicit
4455/// conversion
4456void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004457 // Don't diagnose in unevaluated contexts.
4458 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4459 return;
4460
4461 // Don't diagnose for value- or type-dependent expressions.
4462 if (E->isTypeDependent() || E->isValueDependent())
4463 return;
4464
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004465 // Check for array bounds violations in cases where the check isn't triggered
4466 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4467 // ArraySubscriptExpr is on the RHS of a variable initialization.
4468 CheckArrayAccess(E);
4469
John McCallb4eb64d2010-10-08 02:01:28 +00004470 // This is not the right CC for (e.g.) a variable initialization.
4471 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004472}
4473
John McCall15d7d122010-11-11 03:21:53 +00004474void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4475 FieldDecl *BitField,
4476 Expr *Init) {
4477 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4478}
4479
Mike Stumpf8c49212010-01-21 03:59:47 +00004480/// CheckParmsForFunctionDef - Check that the parameters of the given
4481/// function are appropriate for the definition of a function. This
4482/// takes care of any checks that cannot be performed on the
4483/// declaration itself, e.g., that the types of each of the function
4484/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004485bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4486 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004487 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004488 for (; P != PEnd; ++P) {
4489 ParmVarDecl *Param = *P;
4490
Mike Stumpf8c49212010-01-21 03:59:47 +00004491 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4492 // function declarator that is part of a function definition of
4493 // that function shall not have incomplete type.
4494 //
4495 // This is also C++ [dcl.fct]p6.
4496 if (!Param->isInvalidDecl() &&
4497 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004498 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004499 Param->setInvalidDecl();
4500 HasInvalidParm = true;
4501 }
4502
4503 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4504 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004505 if (CheckParameterNames &&
4506 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004507 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004508 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004509 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004510
4511 // C99 6.7.5.3p12:
4512 // If the function declarator is not part of a definition of that
4513 // function, parameters may have incomplete type and may use the [*]
4514 // notation in their sequences of declarator specifiers to specify
4515 // variable length array types.
4516 QualType PType = Param->getOriginalType();
4517 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4518 if (AT->getSizeModifier() == ArrayType::Star) {
4519 // FIXME: This diagnosic should point the the '[*]' if source-location
4520 // information is added for it.
4521 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4522 }
4523 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004524 }
4525
4526 return HasInvalidParm;
4527}
John McCallb7f4ffe2010-08-12 21:44:57 +00004528
4529/// CheckCastAlign - Implements -Wcast-align, which warns when a
4530/// pointer cast increases the alignment requirements.
4531void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4532 // This is actually a lot of work to potentially be doing on every
4533 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004534 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4535 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004536 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004537 return;
4538
4539 // Ignore dependent types.
4540 if (T->isDependentType() || Op->getType()->isDependentType())
4541 return;
4542
4543 // Require that the destination be a pointer type.
4544 const PointerType *DestPtr = T->getAs<PointerType>();
4545 if (!DestPtr) return;
4546
4547 // If the destination has alignment 1, we're done.
4548 QualType DestPointee = DestPtr->getPointeeType();
4549 if (DestPointee->isIncompleteType()) return;
4550 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4551 if (DestAlign.isOne()) return;
4552
4553 // Require that the source be a pointer type.
4554 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4555 if (!SrcPtr) return;
4556 QualType SrcPointee = SrcPtr->getPointeeType();
4557
4558 // Whitelist casts from cv void*. We already implicitly
4559 // whitelisted casts to cv void*, since they have alignment 1.
4560 // Also whitelist casts involving incomplete types, which implicitly
4561 // includes 'void'.
4562 if (SrcPointee->isIncompleteType()) return;
4563
4564 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4565 if (SrcAlign >= DestAlign) return;
4566
4567 Diag(TRange.getBegin(), diag::warn_cast_align)
4568 << Op->getType() << T
4569 << static_cast<unsigned>(SrcAlign.getQuantity())
4570 << static_cast<unsigned>(DestAlign.getQuantity())
4571 << TRange << Op->getSourceRange();
4572}
4573
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004574static const Type* getElementType(const Expr *BaseExpr) {
4575 const Type* EltType = BaseExpr->getType().getTypePtr();
4576 if (EltType->isAnyPointerType())
4577 return EltType->getPointeeType().getTypePtr();
4578 else if (EltType->isArrayType())
4579 return EltType->getBaseElementTypeUnsafe();
4580 return EltType;
4581}
4582
Chandler Carruthc2684342011-08-05 09:10:50 +00004583/// \brief Check whether this array fits the idiom of a size-one tail padded
4584/// array member of a struct.
4585///
4586/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4587/// commonly used to emulate flexible arrays in C89 code.
4588static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4589 const NamedDecl *ND) {
4590 if (Size != 1 || !ND) return false;
4591
4592 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4593 if (!FD) return false;
4594
4595 // Don't consider sizes resulting from macro expansions or template argument
4596 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004597
4598 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004599 while (TInfo) {
4600 TypeLoc TL = TInfo->getTypeLoc();
4601 // Look through typedefs.
4602 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4603 if (TTL) {
4604 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4605 TInfo = TDL->getTypeSourceInfo();
4606 continue;
4607 }
4608 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4609 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004610 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4611 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004612 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004613 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004614
4615 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004616 if (!RD) return false;
4617 if (RD->isUnion()) return false;
4618 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4619 if (!CRD->isStandardLayout()) return false;
4620 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004621
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004622 // See if this is the last field decl in the record.
4623 const Decl *D = FD;
4624 while ((D = D->getNextDeclInContext()))
4625 if (isa<FieldDecl>(D))
4626 return false;
4627 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004628}
4629
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004630void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004631 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004632 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004633 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004634 if (IndexExpr->isValueDependent())
4635 return;
4636
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004637 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004638 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004639 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004640 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004641 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004642 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004643
Chandler Carruth34064582011-02-17 20:55:08 +00004644 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004645 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004646 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004647 if (IndexNegated)
4648 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004649
Chandler Carruthba447122011-08-05 08:07:29 +00004650 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004651 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4652 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004653 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004654 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004655
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004656 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004657 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004658 if (!size.isStrictlyPositive())
4659 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004660
4661 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004662 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004663 // Make sure we're comparing apples to apples when comparing index to size
4664 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4665 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004666 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004667 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004668 if (ptrarith_typesize != array_typesize) {
4669 // There's a cast to a different size type involved
4670 uint64_t ratio = array_typesize / ptrarith_typesize;
4671 // TODO: Be smarter about handling cases where array_typesize is not a
4672 // multiple of ptrarith_typesize
4673 if (ptrarith_typesize * ratio == array_typesize)
4674 size *= llvm::APInt(size.getBitWidth(), ratio);
4675 }
4676 }
4677
Chandler Carruth34064582011-02-17 20:55:08 +00004678 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004679 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004680 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004681 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004682
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004683 // For array subscripting the index must be less than size, but for pointer
4684 // arithmetic also allow the index (offset) to be equal to size since
4685 // computing the next address after the end of the array is legal and
4686 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004687 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004688 return;
4689
4690 // Also don't warn for arrays of size 1 which are members of some
4691 // structure. These are often used to approximate flexible arrays in C89
4692 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004693 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004694 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004695
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004696 // Suppress the warning if the subscript expression (as identified by the
4697 // ']' location) and the index expression are both from macro expansions
4698 // within a system header.
4699 if (ASE) {
4700 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4701 ASE->getRBracketLoc());
4702 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4703 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4704 IndexExpr->getLocStart());
4705 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4706 return;
4707 }
4708 }
4709
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004710 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004711 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004712 DiagID = diag::warn_array_index_exceeds_bounds;
4713
4714 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4715 PDiag(DiagID) << index.toString(10, true)
4716 << size.toString(10, true)
4717 << (unsigned)size.getLimitedValue(~0U)
4718 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004719 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004720 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004721 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004722 DiagID = diag::warn_ptr_arith_precedes_bounds;
4723 if (index.isNegative()) index = -index;
4724 }
4725
4726 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4727 PDiag(DiagID) << index.toString(10, true)
4728 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004729 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004730
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004731 if (!ND) {
4732 // Try harder to find a NamedDecl to point at in the note.
4733 while (const ArraySubscriptExpr *ASE =
4734 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4735 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4736 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4737 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4738 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4739 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4740 }
4741
Chandler Carruth35001ca2011-02-17 21:10:52 +00004742 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004743 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4744 PDiag(diag::note_array_index_out_of_bounds)
4745 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004746}
4747
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004748void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004749 int AllowOnePastEnd = 0;
4750 while (expr) {
4751 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004752 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004753 case Stmt::ArraySubscriptExprClass: {
4754 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004755 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004756 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004757 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004758 }
4759 case Stmt::UnaryOperatorClass: {
4760 // Only unwrap the * and & unary operators
4761 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4762 expr = UO->getSubExpr();
4763 switch (UO->getOpcode()) {
4764 case UO_AddrOf:
4765 AllowOnePastEnd++;
4766 break;
4767 case UO_Deref:
4768 AllowOnePastEnd--;
4769 break;
4770 default:
4771 return;
4772 }
4773 break;
4774 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004775 case Stmt::ConditionalOperatorClass: {
4776 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4777 if (const Expr *lhs = cond->getLHS())
4778 CheckArrayAccess(lhs);
4779 if (const Expr *rhs = cond->getRHS())
4780 CheckArrayAccess(rhs);
4781 return;
4782 }
4783 default:
4784 return;
4785 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004786 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004787}
John McCallf85e1932011-06-15 23:02:42 +00004788
4789//===--- CHECK: Objective-C retain cycles ----------------------------------//
4790
4791namespace {
4792 struct RetainCycleOwner {
4793 RetainCycleOwner() : Variable(0), Indirect(false) {}
4794 VarDecl *Variable;
4795 SourceRange Range;
4796 SourceLocation Loc;
4797 bool Indirect;
4798
4799 void setLocsFrom(Expr *e) {
4800 Loc = e->getExprLoc();
4801 Range = e->getSourceRange();
4802 }
4803 };
4804}
4805
4806/// Consider whether capturing the given variable can possibly lead to
4807/// a retain cycle.
4808static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4809 // In ARC, it's captured strongly iff the variable has __strong
4810 // lifetime. In MRR, it's captured strongly if the variable is
4811 // __block and has an appropriate type.
4812 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4813 return false;
4814
4815 owner.Variable = var;
4816 owner.setLocsFrom(ref);
4817 return true;
4818}
4819
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004820static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004821 while (true) {
4822 e = e->IgnoreParens();
4823 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4824 switch (cast->getCastKind()) {
4825 case CK_BitCast:
4826 case CK_LValueBitCast:
4827 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004828 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004829 e = cast->getSubExpr();
4830 continue;
4831
John McCallf85e1932011-06-15 23:02:42 +00004832 default:
4833 return false;
4834 }
4835 }
4836
4837 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4838 ObjCIvarDecl *ivar = ref->getDecl();
4839 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4840 return false;
4841
4842 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004843 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004844 return false;
4845
4846 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4847 owner.Indirect = true;
4848 return true;
4849 }
4850
4851 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4852 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4853 if (!var) return false;
4854 return considerVariable(var, ref, owner);
4855 }
4856
John McCallf85e1932011-06-15 23:02:42 +00004857 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4858 if (member->isArrow()) return false;
4859
4860 // Don't count this as an indirect ownership.
4861 e = member->getBase();
4862 continue;
4863 }
4864
John McCall4b9c2d22011-11-06 09:01:30 +00004865 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4866 // Only pay attention to pseudo-objects on property references.
4867 ObjCPropertyRefExpr *pre
4868 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4869 ->IgnoreParens());
4870 if (!pre) return false;
4871 if (pre->isImplicitProperty()) return false;
4872 ObjCPropertyDecl *property = pre->getExplicitProperty();
4873 if (!property->isRetaining() &&
4874 !(property->getPropertyIvarDecl() &&
4875 property->getPropertyIvarDecl()->getType()
4876 .getObjCLifetime() == Qualifiers::OCL_Strong))
4877 return false;
4878
4879 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004880 if (pre->isSuperReceiver()) {
4881 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4882 if (!owner.Variable)
4883 return false;
4884 owner.Loc = pre->getLocation();
4885 owner.Range = pre->getSourceRange();
4886 return true;
4887 }
John McCall4b9c2d22011-11-06 09:01:30 +00004888 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4889 ->getSourceExpr());
4890 continue;
4891 }
4892
John McCallf85e1932011-06-15 23:02:42 +00004893 // Array ivars?
4894
4895 return false;
4896 }
4897}
4898
4899namespace {
4900 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4901 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4902 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4903 Variable(variable), Capturer(0) {}
4904
4905 VarDecl *Variable;
4906 Expr *Capturer;
4907
4908 void VisitDeclRefExpr(DeclRefExpr *ref) {
4909 if (ref->getDecl() == Variable && !Capturer)
4910 Capturer = ref;
4911 }
4912
John McCallf85e1932011-06-15 23:02:42 +00004913 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4914 if (Capturer) return;
4915 Visit(ref->getBase());
4916 if (Capturer && ref->isFreeIvar())
4917 Capturer = ref;
4918 }
4919
4920 void VisitBlockExpr(BlockExpr *block) {
4921 // Look inside nested blocks
4922 if (block->getBlockDecl()->capturesVariable(Variable))
4923 Visit(block->getBlockDecl()->getBody());
4924 }
4925 };
4926}
4927
4928/// Check whether the given argument is a block which captures a
4929/// variable.
4930static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4931 assert(owner.Variable && owner.Loc.isValid());
4932
4933 e = e->IgnoreParenCasts();
4934 BlockExpr *block = dyn_cast<BlockExpr>(e);
4935 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4936 return 0;
4937
4938 FindCaptureVisitor visitor(S.Context, owner.Variable);
4939 visitor.Visit(block->getBlockDecl()->getBody());
4940 return visitor.Capturer;
4941}
4942
4943static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4944 RetainCycleOwner &owner) {
4945 assert(capturer);
4946 assert(owner.Variable && owner.Loc.isValid());
4947
4948 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4949 << owner.Variable << capturer->getSourceRange();
4950 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4951 << owner.Indirect << owner.Range;
4952}
4953
4954/// Check for a keyword selector that starts with the word 'add' or
4955/// 'set'.
4956static bool isSetterLikeSelector(Selector sel) {
4957 if (sel.isUnarySelector()) return false;
4958
Chris Lattner5f9e2722011-07-23 10:55:15 +00004959 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004960 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004961 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004962 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004963 else if (str.startswith("add")) {
4964 // Specially whitelist 'addOperationWithBlock:'.
4965 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4966 return false;
4967 str = str.substr(3);
4968 }
John McCallf85e1932011-06-15 23:02:42 +00004969 else
4970 return false;
4971
4972 if (str.empty()) return true;
4973 return !islower(str.front());
4974}
4975
4976/// Check a message send to see if it's likely to cause a retain cycle.
4977void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4978 // Only check instance methods whose selector looks like a setter.
4979 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4980 return;
4981
4982 // Try to find a variable that the receiver is strongly owned by.
4983 RetainCycleOwner owner;
4984 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004985 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004986 return;
4987 } else {
4988 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4989 owner.Variable = getCurMethodDecl()->getSelfDecl();
4990 owner.Loc = msg->getSuperLoc();
4991 owner.Range = msg->getSuperLoc();
4992 }
4993
4994 // Check whether the receiver is captured by any of the arguments.
4995 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4996 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4997 return diagnoseRetainCycle(*this, capturer, owner);
4998}
4999
5000/// Check a property assign to see if it's likely to cause a retain cycle.
5001void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5002 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005003 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005004 return;
5005
5006 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5007 diagnoseRetainCycle(*this, capturer, owner);
5008}
5009
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005010bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005011 QualType LHS, Expr *RHS) {
5012 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5013 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005014 return false;
5015 // strip off any implicit cast added to get to the one arc-specific
5016 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005017 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005018 Diag(Loc, diag::warn_arc_retained_assign)
5019 << (LT == Qualifiers::OCL_ExplicitNone)
5020 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005021 return true;
5022 }
5023 RHS = cast->getSubExpr();
5024 }
5025 return false;
John McCallf85e1932011-06-15 23:02:42 +00005026}
5027
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005028void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5029 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005030 QualType LHSType;
5031 // PropertyRef on LHS type need be directly obtained from
5032 // its declaration as it has a PsuedoType.
5033 ObjCPropertyRefExpr *PRE
5034 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5035 if (PRE && !PRE->isImplicitProperty()) {
5036 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5037 if (PD)
5038 LHSType = PD->getType();
5039 }
5040
5041 if (LHSType.isNull())
5042 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005043 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5044 return;
5045 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5046 // FIXME. Check for other life times.
5047 if (LT != Qualifiers::OCL_None)
5048 return;
5049
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005050 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005051 if (PRE->isImplicitProperty())
5052 return;
5053 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5054 if (!PD)
5055 return;
5056
5057 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005058 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5059 // when 'assign' attribute was not explicitly specified
5060 // by user, ignore it and rely on property type itself
5061 // for lifetime info.
5062 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5063 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5064 LHSType->isObjCRetainableType())
5065 return;
5066
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005067 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005068 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005069 Diag(Loc, diag::warn_arc_retained_property_assign)
5070 << RHS->getSourceRange();
5071 return;
5072 }
5073 RHS = cast->getSubExpr();
5074 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005075 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005076 }
5077}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005078
5079//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5080
5081namespace {
5082bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5083 SourceLocation StmtLoc,
5084 const NullStmt *Body) {
5085 // Do not warn if the body is a macro that expands to nothing, e.g:
5086 //
5087 // #define CALL(x)
5088 // if (condition)
5089 // CALL(0);
5090 //
5091 if (Body->hasLeadingEmptyMacro())
5092 return false;
5093
5094 // Get line numbers of statement and body.
5095 bool StmtLineInvalid;
5096 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5097 &StmtLineInvalid);
5098 if (StmtLineInvalid)
5099 return false;
5100
5101 bool BodyLineInvalid;
5102 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5103 &BodyLineInvalid);
5104 if (BodyLineInvalid)
5105 return false;
5106
5107 // Warn if null statement and body are on the same line.
5108 if (StmtLine != BodyLine)
5109 return false;
5110
5111 return true;
5112}
5113} // Unnamed namespace
5114
5115void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5116 const Stmt *Body,
5117 unsigned DiagID) {
5118 // Since this is a syntactic check, don't emit diagnostic for template
5119 // instantiations, this just adds noise.
5120 if (CurrentInstantiationScope)
5121 return;
5122
5123 // The body should be a null statement.
5124 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5125 if (!NBody)
5126 return;
5127
5128 // Do the usual checks.
5129 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5130 return;
5131
5132 Diag(NBody->getSemiLoc(), DiagID);
5133 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5134}
5135
5136void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5137 const Stmt *PossibleBody) {
5138 assert(!CurrentInstantiationScope); // Ensured by caller
5139
5140 SourceLocation StmtLoc;
5141 const Stmt *Body;
5142 unsigned DiagID;
5143 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5144 StmtLoc = FS->getRParenLoc();
5145 Body = FS->getBody();
5146 DiagID = diag::warn_empty_for_body;
5147 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5148 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5149 Body = WS->getBody();
5150 DiagID = diag::warn_empty_while_body;
5151 } else
5152 return; // Neither `for' nor `while'.
5153
5154 // The body should be a null statement.
5155 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5156 if (!NBody)
5157 return;
5158
5159 // Skip expensive checks if diagnostic is disabled.
5160 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5161 DiagnosticsEngine::Ignored)
5162 return;
5163
5164 // Do the usual checks.
5165 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5166 return;
5167
5168 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5169 // noise level low, emit diagnostics only if for/while is followed by a
5170 // CompoundStmt, e.g.:
5171 // for (int i = 0; i < n; i++);
5172 // {
5173 // a(i);
5174 // }
5175 // or if for/while is followed by a statement with more indentation
5176 // than for/while itself:
5177 // for (int i = 0; i < n; i++);
5178 // a(i);
5179 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5180 if (!ProbableTypo) {
5181 bool BodyColInvalid;
5182 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5183 PossibleBody->getLocStart(),
5184 &BodyColInvalid);
5185 if (BodyColInvalid)
5186 return;
5187
5188 bool StmtColInvalid;
5189 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5190 S->getLocStart(),
5191 &StmtColInvalid);
5192 if (StmtColInvalid)
5193 return;
5194
5195 if (BodyCol > StmtCol)
5196 ProbableTypo = true;
5197 }
5198
5199 if (ProbableTypo) {
5200 Diag(NBody->getSemiLoc(), DiagID);
5201 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5202 }
5203}