blob: 08af9b71ecd3c4943f78e0106685c8389c6e2ae2 [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"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
47
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000048bool Sema::CheckablePrintfAttr(const FormatAttr *Format, Expr **Args,
49 unsigned NumArgs, bool IsCXXMemberCall) {
50 StringRef Type = Format->getType();
51 // FIXME: add support for "CFString" Type. They are not string literal though,
52 // so they need special handling.
53 if (Type == "printf" || Type == "NSString") return true;
54 if (Type == "printf0") {
Ryan Flynn4403a5e2009-08-06 03:00:50 +000055 // printf0 allows null "format" string; if so don't check format/args
56 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000057 // Does the index refer to the implicit object argument?
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000058 if (IsCXXMemberCall) {
Sebastian Redl4a2614e2009-11-17 18:02:24 +000059 if (format_idx == 0)
60 return false;
61 --format_idx;
62 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +000063 if (format_idx < NumArgs) {
64 Expr *Format = Args[format_idx]->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000065 if (!Format->isNullPointerConstant(Context,
66 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000067 return true;
68 }
69 }
70 return false;
71}
Chris Lattner60800082009-02-18 17:49:48 +000072
John McCall8e10f3b2011-02-26 05:39:39 +000073/// Checks that a call expression's argument count is the desired number.
74/// This is useful when doing custom type-checking. Returns true on error.
75static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
76 unsigned argCount = call->getNumArgs();
77 if (argCount == desiredArgCount) return false;
78
79 if (argCount < desiredArgCount)
80 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
81 << 0 /*function call*/ << desiredArgCount << argCount
82 << call->getSourceRange();
83
84 // Highlight all the excess arguments.
85 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
86 call->getArg(argCount - 1)->getLocEnd());
87
88 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
89 << 0 /*function call*/ << desiredArgCount << argCount
90 << call->getArg(1)->getSourceRange();
91}
92
Julien Lerouge77f68bb2011-09-09 22:41:49 +000093/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
94/// annotation is a non wide string literal.
95static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
96 Arg = Arg->IgnoreParenCasts();
97 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
98 if (!Literal || !Literal->isAscii()) {
99 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
100 << Arg->getSourceRange();
101 return true;
102 }
103 return false;
104}
105
John McCall60d7b3a2010-08-24 06:29:42 +0000106ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000107Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000108 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000109
Chris Lattner946928f2010-10-01 23:23:24 +0000110 // Find out if any arguments are required to be integer constant expressions.
111 unsigned ICEArguments = 0;
112 ASTContext::GetBuiltinTypeError Error;
113 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
114 if (Error != ASTContext::GE_None)
115 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
116
117 // If any arguments are required to be ICE's, check and diagnose.
118 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
119 // Skip arguments not required to be ICE's.
120 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
121
122 llvm::APSInt Result;
123 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
124 return true;
125 ICEArguments &= ~(1 << ArgNo);
126 }
127
Anders Carlssond406bf02009-08-16 01:56:34 +0000128 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000130 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000131 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000132 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000134 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000135 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000136 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 if (SemaBuiltinVAStart(TheCall))
138 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000139 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000140 case Builtin::BI__builtin_isgreater:
141 case Builtin::BI__builtin_isgreaterequal:
142 case Builtin::BI__builtin_isless:
143 case Builtin::BI__builtin_islessequal:
144 case Builtin::BI__builtin_islessgreater:
145 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinUnorderedCompare(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000149 case Builtin::BI__builtin_fpclassify:
150 if (SemaBuiltinFPClassification(TheCall, 6))
151 return ExprError();
152 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000153 case Builtin::BI__builtin_isfinite:
154 case Builtin::BI__builtin_isinf:
155 case Builtin::BI__builtin_isinf_sign:
156 case Builtin::BI__builtin_isnan:
157 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000158 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000159 return ExprError();
160 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000161 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 return SemaBuiltinShuffleVector(TheCall);
163 // TheCall will be freed by the smart pointer here, but that's fine, since
164 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000165 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000166 if (SemaBuiltinPrefetch(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000169 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 if (SemaBuiltinObjectSize(TheCall))
171 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000172 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000173 case Builtin::BI__builtin_longjmp:
174 if (SemaBuiltinLongjmp(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000177
178 case Builtin::BI__builtin_classify_type:
179 if (checkArgCount(*this, TheCall, 1)) return true;
180 TheCall->setType(Context.IntTy);
181 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000182 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000183 if (checkArgCount(*this, TheCall, 1)) return true;
184 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000185 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_add_1:
188 case Builtin::BI__sync_fetch_and_add_2:
189 case Builtin::BI__sync_fetch_and_add_4:
190 case Builtin::BI__sync_fetch_and_add_8:
191 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000192 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000193 case Builtin::BI__sync_fetch_and_sub_1:
194 case Builtin::BI__sync_fetch_and_sub_2:
195 case Builtin::BI__sync_fetch_and_sub_4:
196 case Builtin::BI__sync_fetch_and_sub_8:
197 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000198 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000199 case Builtin::BI__sync_fetch_and_or_1:
200 case Builtin::BI__sync_fetch_and_or_2:
201 case Builtin::BI__sync_fetch_and_or_4:
202 case Builtin::BI__sync_fetch_and_or_8:
203 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000204 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000205 case Builtin::BI__sync_fetch_and_and_1:
206 case Builtin::BI__sync_fetch_and_and_2:
207 case Builtin::BI__sync_fetch_and_and_4:
208 case Builtin::BI__sync_fetch_and_and_8:
209 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000210 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000211 case Builtin::BI__sync_fetch_and_xor_1:
212 case Builtin::BI__sync_fetch_and_xor_2:
213 case Builtin::BI__sync_fetch_and_xor_4:
214 case Builtin::BI__sync_fetch_and_xor_8:
215 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000216 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000217 case Builtin::BI__sync_add_and_fetch_1:
218 case Builtin::BI__sync_add_and_fetch_2:
219 case Builtin::BI__sync_add_and_fetch_4:
220 case Builtin::BI__sync_add_and_fetch_8:
221 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000222 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000223 case Builtin::BI__sync_sub_and_fetch_1:
224 case Builtin::BI__sync_sub_and_fetch_2:
225 case Builtin::BI__sync_sub_and_fetch_4:
226 case Builtin::BI__sync_sub_and_fetch_8:
227 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000228 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000229 case Builtin::BI__sync_and_and_fetch_1:
230 case Builtin::BI__sync_and_and_fetch_2:
231 case Builtin::BI__sync_and_and_fetch_4:
232 case Builtin::BI__sync_and_and_fetch_8:
233 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000234 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000235 case Builtin::BI__sync_or_and_fetch_1:
236 case Builtin::BI__sync_or_and_fetch_2:
237 case Builtin::BI__sync_or_and_fetch_4:
238 case Builtin::BI__sync_or_and_fetch_8:
239 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000240 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000241 case Builtin::BI__sync_xor_and_fetch_1:
242 case Builtin::BI__sync_xor_and_fetch_2:
243 case Builtin::BI__sync_xor_and_fetch_4:
244 case Builtin::BI__sync_xor_and_fetch_8:
245 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000246 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_val_compare_and_swap_1:
248 case Builtin::BI__sync_val_compare_and_swap_2:
249 case Builtin::BI__sync_val_compare_and_swap_4:
250 case Builtin::BI__sync_val_compare_and_swap_8:
251 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000252 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000253 case Builtin::BI__sync_bool_compare_and_swap_1:
254 case Builtin::BI__sync_bool_compare_and_swap_2:
255 case Builtin::BI__sync_bool_compare_and_swap_4:
256 case Builtin::BI__sync_bool_compare_and_swap_8:
257 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000258 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000259 case Builtin::BI__sync_lock_test_and_set_1:
260 case Builtin::BI__sync_lock_test_and_set_2:
261 case Builtin::BI__sync_lock_test_and_set_4:
262 case Builtin::BI__sync_lock_test_and_set_8:
263 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000264 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000265 case Builtin::BI__sync_lock_release_1:
266 case Builtin::BI__sync_lock_release_2:
267 case Builtin::BI__sync_lock_release_4:
268 case Builtin::BI__sync_lock_release_8:
269 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000270 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000271 case Builtin::BI__sync_swap_1:
272 case Builtin::BI__sync_swap_2:
273 case Builtin::BI__sync_swap_4:
274 case Builtin::BI__sync_swap_8:
275 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000276 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000277 case Builtin::BI__atomic_load:
278 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
279 case Builtin::BI__atomic_store:
280 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000281 case Builtin::BI__atomic_init:
282 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000283 case Builtin::BI__atomic_exchange:
284 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
285 case Builtin::BI__atomic_compare_exchange_strong:
286 return SemaAtomicOpsOverloaded(move(TheCallResult),
287 AtomicExpr::CmpXchgStrong);
288 case Builtin::BI__atomic_compare_exchange_weak:
289 return SemaAtomicOpsOverloaded(move(TheCallResult),
290 AtomicExpr::CmpXchgWeak);
291 case Builtin::BI__atomic_fetch_add:
292 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
293 case Builtin::BI__atomic_fetch_sub:
294 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
295 case Builtin::BI__atomic_fetch_and:
296 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
297 case Builtin::BI__atomic_fetch_or:
298 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
299 case Builtin::BI__atomic_fetch_xor:
300 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000301 case Builtin::BI__builtin_annotation:
302 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
303 return ExprError();
304 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000305 }
306
307 // Since the target specific builtins for each arch overlap, only check those
308 // of the arch we are compiling for.
309 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000310 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000311 case llvm::Triple::arm:
312 case llvm::Triple::thumb:
313 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
314 return ExprError();
315 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000316 default:
317 break;
318 }
319 }
320
321 return move(TheCallResult);
322}
323
Nate Begeman61eecf52010-06-14 05:21:25 +0000324// Get the valid immediate range for the specified NEON type code.
325static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000326 NeonTypeFlags Type(t);
327 int IsQuad = Type.isQuad();
328 switch (Type.getEltType()) {
329 case NeonTypeFlags::Int8:
330 case NeonTypeFlags::Poly8:
331 return shift ? 7 : (8 << IsQuad) - 1;
332 case NeonTypeFlags::Int16:
333 case NeonTypeFlags::Poly16:
334 return shift ? 15 : (4 << IsQuad) - 1;
335 case NeonTypeFlags::Int32:
336 return shift ? 31 : (2 << IsQuad) - 1;
337 case NeonTypeFlags::Int64:
338 return shift ? 63 : (1 << IsQuad) - 1;
339 case NeonTypeFlags::Float16:
340 assert(!shift && "cannot shift float types!");
341 return (4 << IsQuad) - 1;
342 case NeonTypeFlags::Float32:
343 assert(!shift && "cannot shift float types!");
344 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000345 }
David Blaikie7530c032012-01-17 06:56:22 +0000346 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000347}
348
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000349/// getNeonEltType - Return the QualType corresponding to the elements of
350/// the vector type specified by the NeonTypeFlags. This is used to check
351/// the pointer arguments for Neon load/store intrinsics.
352static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
353 switch (Flags.getEltType()) {
354 case NeonTypeFlags::Int8:
355 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
356 case NeonTypeFlags::Int16:
357 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
358 case NeonTypeFlags::Int32:
359 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
360 case NeonTypeFlags::Int64:
361 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
362 case NeonTypeFlags::Poly8:
363 return Context.SignedCharTy;
364 case NeonTypeFlags::Poly16:
365 return Context.ShortTy;
366 case NeonTypeFlags::Float16:
367 return Context.UnsignedShortTy;
368 case NeonTypeFlags::Float32:
369 return Context.FloatTy;
370 }
David Blaikie7530c032012-01-17 06:56:22 +0000371 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372}
373
Nate Begeman26a31422010-06-08 02:47:44 +0000374bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000375 llvm::APSInt Result;
376
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000378 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000379 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000380 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000381 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000382#define GET_NEON_OVERLOAD_CHECK
383#include "clang/Basic/arm_neon.inc"
384#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000385 }
386
Nate Begeman0d15c532010-06-13 04:47:52 +0000387 // For NEON intrinsics which are overloaded on vector element type, validate
388 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000389 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000390 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000391 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 return true;
393
Bob Wilsonda95f732011-11-08 01:16:11 +0000394 TV = Result.getLimitedValue(64);
395 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000397 << TheCall->getArg(ImmArg)->getSourceRange();
398 }
399
Bob Wilson46482552011-11-16 21:32:23 +0000400 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000401 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000402 Expr *Arg = TheCall->getArg(PtrArgNum);
403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
404 Arg = ICE->getSubExpr();
405 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
406 QualType RHSTy = RHS.get()->getType();
407 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
408 if (HasConstPtr)
409 EltTy = EltTy.withConst();
410 QualType LHSTy = Context.getPointerType(EltTy);
411 AssignConvertType ConvTy;
412 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
413 if (RHS.isInvalid())
414 return true;
415 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
416 RHS.get(), AA_Assigning))
417 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000418 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000419
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 // For NEON intrinsics which take an immediate value as part of the
421 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000422 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000423 switch (BuiltinID) {
424 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000427 case ARM::BI__builtin_arm_vcvtr_f:
428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000429#define GET_NEON_IMMEDIATE_CHECK
430#include "clang/Basic/arm_neon.inc"
431#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000432 };
433
Nate Begeman61eecf52010-06-14 05:21:25 +0000434 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000435 if (SemaBuiltinConstantArg(TheCall, i, Result))
436 return true;
437
Nate Begeman61eecf52010-06-14 05:21:25 +0000438 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000439 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000440 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000441 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000442 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000443
Nate Begeman99c40bb2010-08-03 21:32:34 +0000444 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000445 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000446}
Daniel Dunbarde454282008-10-02 18:44:07 +0000447
Anders Carlssond406bf02009-08-16 01:56:34 +0000448/// CheckFunctionCall - Check a direct function call for various correctness
449/// and safety properties not strictly enforced by the C type system.
450bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
451 // Get the IdentifierInfo* for the called function.
452 IdentifierInfo *FnInfo = FDecl->getIdentifier();
453
454 // None of the checks below are needed for functions that don't have
455 // simple names (e.g., C++ conversion functions).
456 if (!FnInfo)
457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Daniel Dunbarde454282008-10-02 18:44:07 +0000459 // FIXME: This mechanism should be abstracted to be less fragile and
460 // more efficient. For example, just map function ids to custom
461 // handlers.
462
Ted Kremenekc82faca2010-09-09 04:33:05 +0000463 // Printf and scanf checking.
464 for (specific_attr_iterator<FormatAttr>
465 i = FDecl->specific_attr_begin<FormatAttr>(),
466 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000467 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenekc82faca2010-09-09 04:33:05 +0000470 for (specific_attr_iterator<NonNullAttr>
471 i = FDecl->specific_attr_begin<NonNullAttr>(),
472 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000473 CheckNonNullArguments(*i, TheCall->getArgs(),
474 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000475 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000476
Anna Zaks0a151a12012-01-17 00:37:07 +0000477 unsigned CMId = FDecl->getMemoryFunctionKind();
478 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000479 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000480
Anna Zaksd9b859a2012-01-13 21:52:01 +0000481 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000482 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000483 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000484 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000485 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000486
Anders Carlssond406bf02009-08-16 01:56:34 +0000487 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000488}
489
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000490bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
491 Expr **Args, unsigned NumArgs) {
492 for (specific_attr_iterator<FormatAttr>
493 i = Method->specific_attr_begin<FormatAttr>(),
494 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
495
496 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
497 Method->getSourceRange());
498 }
499
500 // diagnose nonnull arguments.
501 for (specific_attr_iterator<NonNullAttr>
502 i = Method->specific_attr_begin<NonNullAttr>(),
503 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
504 CheckNonNullArguments(*i, Args, lbrac);
505 }
506
507 return false;
508}
509
Anders Carlssond406bf02009-08-16 01:56:34 +0000510bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000511 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
512 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000513 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000515 QualType Ty = V->getType();
516 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000517 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000519 // format string checking.
520 for (specific_attr_iterator<FormatAttr>
521 i = NDecl->specific_attr_begin<FormatAttr>(),
522 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
523 CheckFormatArguments(*i, TheCall);
524 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000525
526 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000527}
528
Eli Friedman276b0612011-10-11 02:20:01 +0000529ExprResult
530Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
531 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
532 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000533
534 // All these operations take one of the following four forms:
535 // T __atomic_load(_Atomic(T)*, int) (loads)
536 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
537 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
538 // (cmpxchg)
539 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
540 // where T is an appropriate type, and the int paremeterss are for orderings.
541 unsigned NumVals = 1;
542 unsigned NumOrders = 1;
543 if (Op == AtomicExpr::Load) {
544 NumVals = 0;
545 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
546 NumVals = 2;
547 NumOrders = 2;
548 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000549 if (Op == AtomicExpr::Init)
550 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000551
552 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
553 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
554 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
555 << TheCall->getCallee()->getSourceRange();
556 return ExprError();
557 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
558 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
559 diag::err_typecheck_call_too_many_args)
560 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
561 << TheCall->getCallee()->getSourceRange();
562 return ExprError();
563 }
564
565 // Inspect the first argument of the atomic operation. This should always be
566 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000567 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000568 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
569 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
570 if (!pointerType) {
571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
572 << Ptr->getType() << Ptr->getSourceRange();
573 return ExprError();
574 }
575
576 QualType AtomTy = pointerType->getPointeeType();
577 if (!AtomTy->isAtomicType()) {
578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
579 << Ptr->getType() << Ptr->getSourceRange();
580 return ExprError();
581 }
582 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
583
584 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
585 !ValType->isIntegerType() && !ValType->isPointerType()) {
586 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
587 << Ptr->getType() << Ptr->getSourceRange();
588 return ExprError();
589 }
590
591 if (!ValType->isIntegerType() &&
592 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
593 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
594 << Ptr->getType() << Ptr->getSourceRange();
595 return ExprError();
596 }
597
598 switch (ValType.getObjCLifetime()) {
599 case Qualifiers::OCL_None:
600 case Qualifiers::OCL_ExplicitNone:
601 // okay
602 break;
603
604 case Qualifiers::OCL_Weak:
605 case Qualifiers::OCL_Strong:
606 case Qualifiers::OCL_Autoreleasing:
607 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
608 << ValType << Ptr->getSourceRange();
609 return ExprError();
610 }
611
612 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000613 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000614 ResultType = Context.VoidTy;
615 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
616 ResultType = Context.BoolTy;
617
618 // The first argument --- the pointer --- has a fixed type; we
619 // deduce the types of the rest of the arguments accordingly. Walk
620 // the remaining arguments, converting them to the deduced value type.
621 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
622 ExprResult Arg = TheCall->getArg(i);
623 QualType Ty;
624 if (i < NumVals+1) {
625 // The second argument to a cmpxchg is a pointer to the data which will
626 // be exchanged. The second argument to a pointer add/subtract is the
627 // amount to add/subtract, which must be a ptrdiff_t. The third
628 // argument to a cmpxchg and the second argument in all other cases
629 // is the type of the value.
630 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
631 Op == AtomicExpr::CmpXchgStrong))
632 Ty = Context.getPointerType(ValType.getUnqualifiedType());
633 else if (!ValType->isIntegerType() &&
634 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
635 Ty = Context.getPointerDiffType();
636 else
637 Ty = ValType;
638 } else {
639 // The order(s) are always converted to int.
640 Ty = Context.IntTy;
641 }
642 InitializedEntity Entity =
643 InitializedEntity::InitializeParameter(Context, Ty, false);
644 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
645 if (Arg.isInvalid())
646 return true;
647 TheCall->setArg(i, Arg.get());
648 }
649
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000650 SmallVector<Expr*, 5> SubExprs;
651 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000652 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000653 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000654 } else if (Op == AtomicExpr::Init) {
655 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000656 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000657 SubExprs.push_back(TheCall->getArg(2)); // Order
658 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000659 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000660 SubExprs.push_back(TheCall->getArg(3)); // Order
661 SubExprs.push_back(TheCall->getArg(1)); // Val1
662 SubExprs.push_back(TheCall->getArg(2)); // Val2
663 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000664 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000665
666 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
667 SubExprs.data(), SubExprs.size(),
668 ResultType, Op,
669 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000670}
671
672
John McCall5f8d6042011-08-27 01:09:30 +0000673/// checkBuiltinArgument - Given a call to a builtin function, perform
674/// normal type-checking on the given argument, updating the call in
675/// place. This is useful when a builtin function requires custom
676/// type-checking for some of its arguments but not necessarily all of
677/// them.
678///
679/// Returns true on error.
680static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
681 FunctionDecl *Fn = E->getDirectCallee();
682 assert(Fn && "builtin call without direct callee!");
683
684 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
685 InitializedEntity Entity =
686 InitializedEntity::InitializeParameter(S.Context, Param);
687
688 ExprResult Arg = E->getArg(0);
689 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
690 if (Arg.isInvalid())
691 return true;
692
693 E->setArg(ArgIndex, Arg.take());
694 return false;
695}
696
Chris Lattner5caa3702009-05-08 06:58:22 +0000697/// SemaBuiltinAtomicOverloaded - We have a call to a function like
698/// __sync_fetch_and_add, which is an overloaded function based on the pointer
699/// type of its first argument. The main ActOnCallExpr routines have already
700/// promoted the types of arguments because all of these calls are prototyped as
701/// void(...).
702///
703/// This function goes through and does final semantic checking for these
704/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000705ExprResult
706Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000707 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000708 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
709 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
710
711 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000712 if (TheCall->getNumArgs() < 1) {
713 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
714 << 0 << 1 << TheCall->getNumArgs()
715 << TheCall->getCallee()->getSourceRange();
716 return ExprError();
717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattner5caa3702009-05-08 06:58:22 +0000719 // Inspect the first argument of the atomic builtin. This should always be
720 // a pointer type, whose element is an integral scalar or pointer type.
721 // Because it is a pointer type, we don't have to worry about any implicit
722 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000723 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000724 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000725 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
726 if (FirstArgResult.isInvalid())
727 return ExprError();
728 FirstArg = FirstArgResult.take();
729 TheCall->setArg(0, FirstArg);
730
John McCallf85e1932011-06-15 23:02:42 +0000731 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
732 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000733 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
734 << FirstArg->getType() << FirstArg->getSourceRange();
735 return ExprError();
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
John McCallf85e1932011-06-15 23:02:42 +0000738 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000740 !ValType->isBlockPointerType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
742 << FirstArg->getType() << FirstArg->getSourceRange();
743 return ExprError();
744 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000745
John McCallf85e1932011-06-15 23:02:42 +0000746 switch (ValType.getObjCLifetime()) {
747 case Qualifiers::OCL_None:
748 case Qualifiers::OCL_ExplicitNone:
749 // okay
750 break;
751
752 case Qualifiers::OCL_Weak:
753 case Qualifiers::OCL_Strong:
754 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000755 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000756 << ValType << FirstArg->getSourceRange();
757 return ExprError();
758 }
759
John McCallb45ae252011-10-05 07:41:44 +0000760 // Strip any qualifiers off ValType.
761 ValType = ValType.getUnqualifiedType();
762
Chandler Carruth8d13d222010-07-18 20:54:12 +0000763 // The majority of builtins return a value, but a few have special return
764 // types, so allow them to override appropriately below.
765 QualType ResultType = ValType;
766
Chris Lattner5caa3702009-05-08 06:58:22 +0000767 // We need to figure out which concrete builtin this maps onto. For example,
768 // __sync_fetch_and_add with a 2 byte object turns into
769 // __sync_fetch_and_add_2.
770#define BUILTIN_ROW(x) \
771 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
772 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Chris Lattner5caa3702009-05-08 06:58:22 +0000774 static const unsigned BuiltinIndices[][5] = {
775 BUILTIN_ROW(__sync_fetch_and_add),
776 BUILTIN_ROW(__sync_fetch_and_sub),
777 BUILTIN_ROW(__sync_fetch_and_or),
778 BUILTIN_ROW(__sync_fetch_and_and),
779 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattner5caa3702009-05-08 06:58:22 +0000781 BUILTIN_ROW(__sync_add_and_fetch),
782 BUILTIN_ROW(__sync_sub_and_fetch),
783 BUILTIN_ROW(__sync_and_and_fetch),
784 BUILTIN_ROW(__sync_or_and_fetch),
785 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 BUILTIN_ROW(__sync_val_compare_and_swap),
788 BUILTIN_ROW(__sync_bool_compare_and_swap),
789 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000790 BUILTIN_ROW(__sync_lock_release),
791 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000792 };
Mike Stump1eb44332009-09-09 15:08:12 +0000793#undef BUILTIN_ROW
794
Chris Lattner5caa3702009-05-08 06:58:22 +0000795 // Determine the index of the size.
796 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000797 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000798 case 1: SizeIndex = 0; break;
799 case 2: SizeIndex = 1; break;
800 case 4: SizeIndex = 2; break;
801 case 8: SizeIndex = 3; break;
802 case 16: SizeIndex = 4; break;
803 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000804 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
805 << FirstArg->getType() << FirstArg->getSourceRange();
806 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner5caa3702009-05-08 06:58:22 +0000809 // Each of these builtins has one pointer argument, followed by some number of
810 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
811 // that we ignore. Find out which row of BuiltinIndices to read from as well
812 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000813 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000814 unsigned BuiltinIndex, NumFixed = 1;
815 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000816 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000817 case Builtin::BI__sync_fetch_and_add:
818 case Builtin::BI__sync_fetch_and_add_1:
819 case Builtin::BI__sync_fetch_and_add_2:
820 case Builtin::BI__sync_fetch_and_add_4:
821 case Builtin::BI__sync_fetch_and_add_8:
822 case Builtin::BI__sync_fetch_and_add_16:
823 BuiltinIndex = 0;
824 break;
825
826 case Builtin::BI__sync_fetch_and_sub:
827 case Builtin::BI__sync_fetch_and_sub_1:
828 case Builtin::BI__sync_fetch_and_sub_2:
829 case Builtin::BI__sync_fetch_and_sub_4:
830 case Builtin::BI__sync_fetch_and_sub_8:
831 case Builtin::BI__sync_fetch_and_sub_16:
832 BuiltinIndex = 1;
833 break;
834
835 case Builtin::BI__sync_fetch_and_or:
836 case Builtin::BI__sync_fetch_and_or_1:
837 case Builtin::BI__sync_fetch_and_or_2:
838 case Builtin::BI__sync_fetch_and_or_4:
839 case Builtin::BI__sync_fetch_and_or_8:
840 case Builtin::BI__sync_fetch_and_or_16:
841 BuiltinIndex = 2;
842 break;
843
844 case Builtin::BI__sync_fetch_and_and:
845 case Builtin::BI__sync_fetch_and_and_1:
846 case Builtin::BI__sync_fetch_and_and_2:
847 case Builtin::BI__sync_fetch_and_and_4:
848 case Builtin::BI__sync_fetch_and_and_8:
849 case Builtin::BI__sync_fetch_and_and_16:
850 BuiltinIndex = 3;
851 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregora9766412011-11-28 16:30:08 +0000853 case Builtin::BI__sync_fetch_and_xor:
854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
859 BuiltinIndex = 4;
860 break;
861
862 case Builtin::BI__sync_add_and_fetch:
863 case Builtin::BI__sync_add_and_fetch_1:
864 case Builtin::BI__sync_add_and_fetch_2:
865 case Builtin::BI__sync_add_and_fetch_4:
866 case Builtin::BI__sync_add_and_fetch_8:
867 case Builtin::BI__sync_add_and_fetch_16:
868 BuiltinIndex = 5;
869 break;
870
871 case Builtin::BI__sync_sub_and_fetch:
872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
877 BuiltinIndex = 6;
878 break;
879
880 case Builtin::BI__sync_and_and_fetch:
881 case Builtin::BI__sync_and_and_fetch_1:
882 case Builtin::BI__sync_and_and_fetch_2:
883 case Builtin::BI__sync_and_and_fetch_4:
884 case Builtin::BI__sync_and_and_fetch_8:
885 case Builtin::BI__sync_and_and_fetch_16:
886 BuiltinIndex = 7;
887 break;
888
889 case Builtin::BI__sync_or_and_fetch:
890 case Builtin::BI__sync_or_and_fetch_1:
891 case Builtin::BI__sync_or_and_fetch_2:
892 case Builtin::BI__sync_or_and_fetch_4:
893 case Builtin::BI__sync_or_and_fetch_8:
894 case Builtin::BI__sync_or_and_fetch_16:
895 BuiltinIndex = 8;
896 break;
897
898 case Builtin::BI__sync_xor_and_fetch:
899 case Builtin::BI__sync_xor_and_fetch_1:
900 case Builtin::BI__sync_xor_and_fetch_2:
901 case Builtin::BI__sync_xor_and_fetch_4:
902 case Builtin::BI__sync_xor_and_fetch_8:
903 case Builtin::BI__sync_xor_and_fetch_16:
904 BuiltinIndex = 9;
905 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner5caa3702009-05-08 06:58:22 +0000907 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000908 case Builtin::BI__sync_val_compare_and_swap_1:
909 case Builtin::BI__sync_val_compare_and_swap_2:
910 case Builtin::BI__sync_val_compare_and_swap_4:
911 case Builtin::BI__sync_val_compare_and_swap_8:
912 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000913 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000914 NumFixed = 2;
915 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000916
Chris Lattner5caa3702009-05-08 06:58:22 +0000917 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000918 case Builtin::BI__sync_bool_compare_and_swap_1:
919 case Builtin::BI__sync_bool_compare_and_swap_2:
920 case Builtin::BI__sync_bool_compare_and_swap_4:
921 case Builtin::BI__sync_bool_compare_and_swap_8:
922 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000923 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000924 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000925 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000926 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000927
928 case Builtin::BI__sync_lock_test_and_set:
929 case Builtin::BI__sync_lock_test_and_set_1:
930 case Builtin::BI__sync_lock_test_and_set_2:
931 case Builtin::BI__sync_lock_test_and_set_4:
932 case Builtin::BI__sync_lock_test_and_set_8:
933 case Builtin::BI__sync_lock_test_and_set_16:
934 BuiltinIndex = 12;
935 break;
936
Chris Lattner5caa3702009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000943 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000945 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000946 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000947
948 case Builtin::BI__sync_swap:
949 case Builtin::BI__sync_swap_1:
950 case Builtin::BI__sync_swap_2:
951 case Builtin::BI__sync_swap_4:
952 case Builtin::BI__sync_swap_8:
953 case Builtin::BI__sync_swap_16:
954 BuiltinIndex = 14;
955 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner5caa3702009-05-08 06:58:22 +0000958 // Now that we know how many fixed arguments we expect, first check that we
959 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000960 if (TheCall->getNumArgs() < 1+NumFixed) {
961 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
962 << 0 << 1+NumFixed << TheCall->getNumArgs()
963 << TheCall->getCallee()->getSourceRange();
964 return ExprError();
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000967 // Get the decl for the concrete builtin from this, we can tell what the
968 // concrete integer type we should convert to is.
969 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
970 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
971 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000972 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000973 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
974 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000975
John McCallf871d0c2010-08-07 06:22:56 +0000976 // The first argument --- the pointer --- has a fixed type; we
977 // deduce the types of the rest of the arguments accordingly. Walk
978 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000979 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000980 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner5caa3702009-05-08 06:58:22 +0000982 // GCC does an implicit conversion to the pointer or integer ValType. This
983 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000984 // Initialize the argument.
985 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
986 ValType, /*consume*/ false);
987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000988 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000989 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner5caa3702009-05-08 06:58:22 +0000991 // Okay, we have something that *can* be converted to the right type. Check
992 // to see if there is a potentially weird extension going on here. This can
993 // happen when you do an atomic operation on something like an char* and
994 // pass in 42. The 42 gets converted to char. This is even more strange
995 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000996 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000997 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001000 ASTContext& Context = this->getASTContext();
1001
1002 // Create a new DeclRefExpr to refer to the new decl.
1003 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1004 Context,
1005 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001006 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001007 NewBuiltinDecl,
1008 DRE->getLocation(),
1009 NewBuiltinDecl->getType(),
1010 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner5caa3702009-05-08 06:58:22 +00001012 // Set the callee in the CallExpr.
1013 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001014 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001015 if (PromotedCall.isInvalid())
1016 return ExprError();
1017 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001019 // Change the result type of the call to match the original value type. This
1020 // is arbitrary, but the codegen for these builtins ins design to handle it
1021 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001022 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001023
1024 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001025}
1026
Chris Lattner69039812009-02-18 06:01:06 +00001027/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001028/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001029/// Note: It might also make sense to do the UTF-16 conversion here (would
1030/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001031bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001032 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001033 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1034
Douglas Gregor5cee1192011-07-27 05:40:30 +00001035 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001036 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1037 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001038 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001041 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001042 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001043 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001044 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001045 const UTF8 *FromPtr = (UTF8 *)String.data();
1046 UTF16 *ToPtr = &ToBuf[0];
1047
1048 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1049 &ToPtr, ToPtr + NumBytes,
1050 strictConversion);
1051 // Check for conversion failure.
1052 if (Result != conversionOK)
1053 Diag(Arg->getLocStart(),
1054 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1055 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001056 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001057}
1058
Chris Lattnerc27c6652007-12-20 00:05:45 +00001059/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1060/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001061bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1062 Expr *Fn = TheCall->getCallee();
1063 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001064 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001065 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001066 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1067 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001068 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001069 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001070 return true;
1071 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001072
1073 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001074 return Diag(TheCall->getLocEnd(),
1075 diag::err_typecheck_call_too_few_args_at_least)
1076 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001077 }
1078
John McCall5f8d6042011-08-27 01:09:30 +00001079 // Type-check the first argument normally.
1080 if (checkBuiltinArgument(*this, TheCall, 0))
1081 return true;
1082
Chris Lattnerc27c6652007-12-20 00:05:45 +00001083 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001084 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001085 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001086 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001087 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001088 else if (FunctionDecl *FD = getCurFunctionDecl())
1089 isVariadic = FD->isVariadic();
1090 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001091 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Chris Lattnerc27c6652007-12-20 00:05:45 +00001093 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001094 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1095 return true;
1096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Chris Lattner30ce3442007-12-19 23:59:04 +00001098 // Verify that the second argument to the builtin is the last argument of the
1099 // current function or method.
1100 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001101 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Anders Carlsson88cf2262008-02-11 04:20:54 +00001103 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1104 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001105 // FIXME: This isn't correct for methods (results in bogus warning).
1106 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001107 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001108 if (CurBlock)
1109 LastArg = *(CurBlock->TheDecl->param_end()-1);
1110 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001111 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001112 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001113 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001114 SecondArgIsLastNamedArgument = PV == LastArg;
1115 }
1116 }
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Chris Lattner30ce3442007-12-19 23:59:04 +00001118 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001119 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001120 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1121 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001122}
Chris Lattner30ce3442007-12-19 23:59:04 +00001123
Chris Lattner1b9a0792007-12-20 00:26:33 +00001124/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1125/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001126bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1127 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001128 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001129 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001130 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001131 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001132 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001133 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001134 << SourceRange(TheCall->getArg(2)->getLocStart(),
1135 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001136
John Wiegley429bb272011-04-08 18:41:53 +00001137 ExprResult OrigArg0 = TheCall->getArg(0);
1138 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001139
Chris Lattner1b9a0792007-12-20 00:26:33 +00001140 // Do standard promotions between the two arguments, returning their common
1141 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001142 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001143 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1144 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001145
1146 // Make sure any conversions are pushed back into the call; this is
1147 // type safe since unordered compare builtins are declared as "_Bool
1148 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001149 TheCall->setArg(0, OrigArg0.get());
1150 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001151
John Wiegley429bb272011-04-08 18:41:53 +00001152 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001153 return false;
1154
Chris Lattner1b9a0792007-12-20 00:26:33 +00001155 // If the common type isn't a real floating type, then the arguments were
1156 // invalid for this operation.
1157 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001158 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001159 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001160 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1161 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Chris Lattner1b9a0792007-12-20 00:26:33 +00001163 return false;
1164}
1165
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001166/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1167/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001168/// to check everything. We expect the last argument to be a floating point
1169/// value.
1170bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1171 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001172 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001173 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001174 if (TheCall->getNumArgs() > NumArgs)
1175 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001176 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001177 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001178 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001179 (*(TheCall->arg_end()-1))->getLocEnd());
1180
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001181 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Eli Friedman9ac6f622009-08-31 20:06:00 +00001183 if (OrigArg->isTypeDependent())
1184 return false;
1185
Chris Lattner81368fb2010-05-06 05:50:07 +00001186 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001187 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001188 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001189 diag::err_typecheck_call_invalid_unary_fp)
1190 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattner81368fb2010-05-06 05:50:07 +00001192 // If this is an implicit conversion from float -> double, remove it.
1193 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1194 Expr *CastArg = Cast->getSubExpr();
1195 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1196 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1197 "promotion from float to double is the only expected cast here");
1198 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001199 TheCall->setArg(NumArgs-1, CastArg);
1200 OrigArg = CastArg;
1201 }
1202 }
1203
Eli Friedman9ac6f622009-08-31 20:06:00 +00001204 return false;
1205}
1206
Eli Friedmand38617c2008-05-14 19:38:39 +00001207/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1208// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001209ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001210 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001211 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001212 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001213 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001214 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001215
Nate Begeman37b6a572010-06-08 00:16:34 +00001216 // Determine which of the following types of shufflevector we're checking:
1217 // 1) unary, vector mask: (lhs, mask)
1218 // 2) binary, vector mask: (lhs, rhs, mask)
1219 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1220 QualType resType = TheCall->getArg(0)->getType();
1221 unsigned numElements = 0;
1222
Douglas Gregorcde01732009-05-19 22:10:17 +00001223 if (!TheCall->getArg(0)->isTypeDependent() &&
1224 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001225 QualType LHSType = TheCall->getArg(0)->getType();
1226 QualType RHSType = TheCall->getArg(1)->getType();
1227
1228 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001229 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001230 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001231 TheCall->getArg(1)->getLocEnd());
1232 return ExprError();
1233 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001234
1235 numElements = LHSType->getAs<VectorType>()->getNumElements();
1236 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Nate Begeman37b6a572010-06-08 00:16:34 +00001238 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1239 // with mask. If so, verify that RHS is an integer vector type with the
1240 // same number of elts as lhs.
1241 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001242 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001243 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1244 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1245 << SourceRange(TheCall->getArg(1)->getLocStart(),
1246 TheCall->getArg(1)->getLocEnd());
1247 numResElements = numElements;
1248 }
1249 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001250 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001251 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001252 TheCall->getArg(1)->getLocEnd());
1253 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001254 } else if (numElements != numResElements) {
1255 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001256 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001257 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001258 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001259 }
1260
1261 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001262 if (TheCall->getArg(i)->isTypeDependent() ||
1263 TheCall->getArg(i)->isValueDependent())
1264 continue;
1265
Nate Begeman37b6a572010-06-08 00:16:34 +00001266 llvm::APSInt Result(32);
1267 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1268 return ExprError(Diag(TheCall->getLocStart(),
1269 diag::err_shufflevector_nonconstant_argument)
1270 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001271
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001272 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001273 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001274 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001275 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001276 }
1277
Chris Lattner5f9e2722011-07-23 10:55:15 +00001278 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001279
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001280 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001281 exprs.push_back(TheCall->getArg(i));
1282 TheCall->setArg(i, 0);
1283 }
1284
Nate Begemana88dc302009-08-12 02:10:25 +00001285 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001286 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001287 TheCall->getCallee()->getLocStart(),
1288 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001289}
Chris Lattner30ce3442007-12-19 23:59:04 +00001290
Daniel Dunbar4493f792008-07-21 22:59:13 +00001291/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1292// This is declared to take (const void*, ...) and can take two
1293// optional constant int args.
1294bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001295 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001296
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001297 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001298 return Diag(TheCall->getLocEnd(),
1299 diag::err_typecheck_call_too_many_args_at_most)
1300 << 0 /*function call*/ << 3 << NumArgs
1301 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001302
1303 // Argument 0 is checked for us and the remaining arguments must be
1304 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001305 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001306 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001307
Eli Friedman9aef7262009-12-04 00:30:06 +00001308 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001309 if (SemaBuiltinConstantArg(TheCall, i, Result))
1310 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Daniel Dunbar4493f792008-07-21 22:59:13 +00001312 // FIXME: gcc issues a warning and rewrites these to 0. These
1313 // seems especially odd for the third argument since the default
1314 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001315 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001316 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001317 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001318 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001319 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001320 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001321 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001322 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001323 }
1324 }
1325
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001326 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001327}
1328
Eric Christopher691ebc32010-04-17 02:26:23 +00001329/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1330/// TheCall is a constant expression.
1331bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1332 llvm::APSInt &Result) {
1333 Expr *Arg = TheCall->getArg(ArgNum);
1334 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1335 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1336
1337 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1338
1339 if (!Arg->isIntegerConstantExpr(Result, Context))
1340 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001341 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001342
Chris Lattner21fb98e2009-09-23 06:06:36 +00001343 return false;
1344}
1345
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001346/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1347/// int type). This simply type checks that type is one of the defined
1348/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001349// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001350bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001351 llvm::APSInt Result;
1352
1353 // Check constant-ness first.
1354 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1355 return true;
1356
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001357 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001358 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001359 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1360 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001361 }
1362
1363 return false;
1364}
1365
Eli Friedman586d6a82009-05-03 06:04:26 +00001366/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001367/// This checks that val is a constant 1.
1368bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1369 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001370 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001371
Eric Christopher691ebc32010-04-17 02:26:23 +00001372 // TODO: This is less than ideal. Overload this to take a value.
1373 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1374 return true;
1375
1376 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001377 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1378 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1379
1380 return false;
1381}
1382
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001383// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001384bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1385 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001386 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001387 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001388 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001389 if (E->isTypeDependent() || E->isValueDependent())
1390 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001391
Peter Collingbournef111d932011-04-15 00:35:48 +00001392 E = E->IgnoreParens();
1393
Ted Kremenekd30ef872009-01-12 23:09:09 +00001394 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001395 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001396 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001397 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001398 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001399 format_idx, firstDataArg, isPrintf,
1400 inFunctionCall)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001401 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001402 format_idx, firstDataArg, isPrintf,
1403 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001404 }
1405
Ted Kremenek95355bb2010-09-09 03:51:42 +00001406 case Stmt::IntegerLiteralClass:
1407 // Technically -Wformat-nonliteral does not warn about this case.
1408 // The behavior of printf and friends in this case is implementation
1409 // dependent. Ideally if the format string cannot be null then
1410 // it should have a 'nonnull' attribute in the function prototype.
1411 return true;
1412
Ted Kremenekd30ef872009-01-12 23:09:09 +00001413 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001414 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1415 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001416 }
1417
John McCall56ca35d2011-02-17 10:25:35 +00001418 case Stmt::OpaqueValueExprClass:
1419 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1420 E = src;
1421 goto tryAgain;
1422 }
1423 return false;
1424
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001425 case Stmt::PredefinedExprClass:
1426 // While __func__, etc., are technically not string literals, they
1427 // cannot contain format specifiers and thus are not a security
1428 // liability.
1429 return true;
1430
Ted Kremenek082d9362009-03-20 21:35:28 +00001431 case Stmt::DeclRefExprClass: {
1432 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Ted Kremenek082d9362009-03-20 21:35:28 +00001434 // As an exception, do not flag errors for variables binding to
1435 // const string literals.
1436 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1437 bool isConstant = false;
1438 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001439
Ted Kremenek082d9362009-03-20 21:35:28 +00001440 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1441 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001442 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001443 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001444 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001445 } else if (T->isObjCObjectPointerType()) {
1446 // In ObjC, there is usually no "const ObjectPointer" type,
1447 // so don't check if the pointee type is constant.
1448 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Ted Kremenek082d9362009-03-20 21:35:28 +00001451 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001452 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001453 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001454 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001455 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Anders Carlssond966a552009-06-28 19:55:58 +00001458 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1459 // special check to see if the format string is a function parameter
1460 // of the function calling the printf function. If the function
1461 // has an attribute indicating it is a printf-like function, then we
1462 // should suppress warnings concerning non-literals being used in a call
1463 // to a vprintf function. For example:
1464 //
1465 // void
1466 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1467 // va_list ap;
1468 // va_start(ap, fmt);
1469 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1470 // ...
1471 //
1472 //
1473 // FIXME: We don't have full attribute support yet, so just check to see
1474 // if the argument is a DeclRefExpr that references a parameter. We'll
1475 // add proper support for checking the attribute later.
1476 if (HasVAListArg)
1477 if (isa<ParmVarDecl>(VD))
1478 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Ted Kremenek082d9362009-03-20 21:35:28 +00001481 return false;
1482 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001483
Anders Carlsson8f031b32009-06-27 04:05:33 +00001484 case Stmt::CallExprClass: {
1485 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001486 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001487 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1488 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001490 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001491 unsigned ArgIndex = FA->getFormatIdx();
1492 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001494 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001495 format_idx, firstDataArg, isPrintf,
1496 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001497 }
1498 }
1499 }
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Anders Carlsson8f031b32009-06-27 04:05:33 +00001502 return false;
1503 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001504 case Stmt::ObjCStringLiteralClass:
1505 case Stmt::StringLiteralClass: {
1506 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Ted Kremenek082d9362009-03-20 21:35:28 +00001508 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001509 StrE = ObjCFExpr->getString();
1510 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001511 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Ted Kremenekd30ef872009-01-12 23:09:09 +00001513 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001514 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001515 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001516 return true;
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenekd30ef872009-01-12 23:09:09 +00001519 return false;
1520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremenek082d9362009-03-20 21:35:28 +00001522 default:
1523 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001524 }
1525}
1526
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001527void
Mike Stump1eb44332009-09-09 15:08:12 +00001528Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001529 const Expr * const *ExprArgs,
1530 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001531 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1532 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001533 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001534 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001535 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001536 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001537 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001538 }
1539}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001540
Ted Kremenek826a3452010-07-16 02:11:22 +00001541/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1542/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001543void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1544 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001545 // The way the format attribute works in GCC, the implicit this argument
1546 // of member functions is counted. However, it doesn't appear in our own
1547 // lists, so decrement format_idx in that case.
1548 if (isa<CXXMemberCallExpr>(TheCall)) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001549 const CXXMethodDecl *method_decl =
1550 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1551 IsCXXMember = method_decl && method_decl->isInstance();
1552 }
1553 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1554 IsCXXMember, TheCall->getRParenLoc(),
1555 TheCall->getCallee()->getSourceRange());
1556}
1557
1558void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1559 unsigned NumArgs, bool IsCXXMember,
1560 SourceLocation Loc, SourceRange Range) {
1561 const bool b = Format->getType() == "scanf";
1562 if (b || CheckablePrintfAttr(Format, Args, NumArgs, IsCXXMember)) {
1563 bool HasVAListArg = Format->getFirstArg() == 0;
1564 unsigned format_idx = Format->getFormatIdx() - 1;
1565 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1566 if (IsCXXMember) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001567 if (format_idx == 0)
1568 return;
1569 --format_idx;
1570 if(firstDataArg != 0)
1571 --firstDataArg;
1572 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001573 CheckPrintfScanfArguments(Args, NumArgs, HasVAListArg, format_idx,
1574 firstDataArg, !b, Loc, Range);
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001575 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001576}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001577
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001578void Sema::CheckPrintfScanfArguments(Expr **Args, unsigned NumArgs,
1579 bool HasVAListArg, unsigned format_idx,
1580 unsigned firstDataArg, bool isPrintf,
1581 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001582 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001583 if (format_idx >= NumArgs) {
1584 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001585 return;
1586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001588 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattner59907c42007-08-10 20:18:51 +00001590 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001591 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001592 // Dynamically generated format strings are difficult to
1593 // automatically vet at compile time. Requiring that format strings
1594 // are string literals: (1) permits the checking of format strings by
1595 // the compiler and thereby (2) can practically remove the source of
1596 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001597
Mike Stump1eb44332009-09-09 15:08:12 +00001598 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001599 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001600 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001601 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001602 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1603 format_idx, firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001604 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001605
Chris Lattner655f1412009-04-29 04:59:47 +00001606 // If there are no arguments specified, warn with -Wformat-security, otherwise
1607 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001608 if (NumArgs == format_idx+1)
1609 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001610 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001611 << OrigFormatExpr->getSourceRange();
1612 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001613 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001614 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001615 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001616}
Ted Kremenek71895b92007-08-14 17:39:48 +00001617
Ted Kremeneke0e53132010-01-28 23:39:18 +00001618namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001619class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1620protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001621 Sema &S;
1622 const StringLiteral *FExpr;
1623 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001624 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001625 const unsigned NumDataArgs;
1626 const bool IsObjCLiteral;
1627 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001628 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001629 const Expr * const *Args;
1630 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001631 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001632 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001633 bool usesPositionalArgs;
1634 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001635 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001636public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001637 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001638 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001639 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001640 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001641 Expr **args, unsigned numArgs,
1642 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001643 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001644 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001645 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001646 IsObjCLiteral(isObjCLiteral), Beg(beg),
1647 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001648 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001649 usesPositionalArgs(false), atFirstArg(true),
1650 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001651 CoveredArgs.resize(numDataArgs);
1652 CoveredArgs.reset();
1653 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001654
Ted Kremenek07d161f2010-01-29 01:50:07 +00001655 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001656
Ted Kremenek826a3452010-07-16 02:11:22 +00001657 void HandleIncompleteSpecifier(const char *startSpecifier,
1658 unsigned specifierLen);
1659
Ted Kremenekefaff192010-02-27 01:41:03 +00001660 virtual void HandleInvalidPosition(const char *startSpecifier,
1661 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001662 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001663
1664 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1665
Ted Kremeneke0e53132010-01-28 23:39:18 +00001666 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001667
Richard Trieu55733de2011-10-28 00:41:25 +00001668 template <typename Range>
1669 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1670 const Expr *ArgumentExpr,
1671 PartialDiagnostic PDiag,
1672 SourceLocation StringLoc,
1673 bool IsStringLocation, Range StringRange,
1674 FixItHint Fixit = FixItHint());
1675
Ted Kremenek826a3452010-07-16 02:11:22 +00001676protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001677 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1678 const char *startSpec,
1679 unsigned specifierLen,
1680 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001681
1682 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1683 const char *startSpec,
1684 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001685
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001686 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001687 CharSourceRange getSpecifierRange(const char *startSpecifier,
1688 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001689 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001690
Ted Kremenek0d277352010-01-29 01:06:55 +00001691 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001692
1693 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1694 const analyze_format_string::ConversionSpecifier &CS,
1695 const char *startSpecifier, unsigned specifierLen,
1696 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001697
1698 template <typename Range>
1699 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1700 bool IsStringLocation, Range StringRange,
1701 FixItHint Fixit = FixItHint());
1702
1703 void CheckPositionalAndNonpositionalArgs(
1704 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001705};
1706}
1707
Ted Kremenek826a3452010-07-16 02:11:22 +00001708SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001709 return OrigFormatExpr->getSourceRange();
1710}
1711
Ted Kremenek826a3452010-07-16 02:11:22 +00001712CharSourceRange CheckFormatHandler::
1713getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001714 SourceLocation Start = getLocationOfByte(startSpecifier);
1715 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1716
1717 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001718 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001719
1720 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001721}
1722
Ted Kremenek826a3452010-07-16 02:11:22 +00001723SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001724 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001725}
1726
Ted Kremenek826a3452010-07-16 02:11:22 +00001727void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1728 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001729 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1730 getLocationOfByte(startSpecifier),
1731 /*IsStringLocation*/true,
1732 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001733}
1734
Ted Kremenekefaff192010-02-27 01:41:03 +00001735void
Ted Kremenek826a3452010-07-16 02:11:22 +00001736CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1737 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1739 << (unsigned) p,
1740 getLocationOfByte(startPos), /*IsStringLocation*/true,
1741 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001742}
1743
Ted Kremenek826a3452010-07-16 02:11:22 +00001744void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001745 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001746 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1747 getLocationOfByte(startPos),
1748 /*IsStringLocation*/true,
1749 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001750}
1751
Ted Kremenek826a3452010-07-16 02:11:22 +00001752void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001753 if (!IsObjCLiteral) {
1754 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001755 EmitFormatDiagnostic(
1756 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1757 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1758 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001759 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001760}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001761
Ted Kremenek826a3452010-07-16 02:11:22 +00001762const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001763 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001764}
1765
1766void CheckFormatHandler::DoneProcessing() {
1767 // Does the number of data arguments exceed the number of
1768 // format conversions in the format string?
1769 if (!HasVAListArg) {
1770 // Find any arguments that weren't covered.
1771 CoveredArgs.flip();
1772 signed notCoveredArg = CoveredArgs.find_first();
1773 if (notCoveredArg >= 0) {
1774 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1776 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1777 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001778 }
1779 }
1780}
1781
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001782bool
1783CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1784 SourceLocation Loc,
1785 const char *startSpec,
1786 unsigned specifierLen,
1787 const char *csStart,
1788 unsigned csLen) {
1789
1790 bool keepGoing = true;
1791 if (argIndex < NumDataArgs) {
1792 // Consider the argument coverered, even though the specifier doesn't
1793 // make sense.
1794 CoveredArgs.set(argIndex);
1795 }
1796 else {
1797 // If argIndex exceeds the number of data arguments we
1798 // don't issue a warning because that is just a cascade of warnings (and
1799 // they may have intended '%%' anyway). We don't want to continue processing
1800 // the format string after this point, however, as we will like just get
1801 // gibberish when trying to match arguments.
1802 keepGoing = false;
1803 }
1804
Richard Trieu55733de2011-10-28 00:41:25 +00001805 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1806 << StringRef(csStart, csLen),
1807 Loc, /*IsStringLocation*/true,
1808 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001809
1810 return keepGoing;
1811}
1812
Richard Trieu55733de2011-10-28 00:41:25 +00001813void
1814CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1815 const char *startSpec,
1816 unsigned specifierLen) {
1817 EmitFormatDiagnostic(
1818 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1819 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1820}
1821
Ted Kremenek666a1972010-07-26 19:45:42 +00001822bool
1823CheckFormatHandler::CheckNumArgs(
1824 const analyze_format_string::FormatSpecifier &FS,
1825 const analyze_format_string::ConversionSpecifier &CS,
1826 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1827
1828 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001829 PartialDiagnostic PDiag = FS.usesPositionalArg()
1830 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1831 << (argIndex+1) << NumDataArgs)
1832 : S.PDiag(diag::warn_printf_insufficient_data_args);
1833 EmitFormatDiagnostic(
1834 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1835 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001836 return false;
1837 }
1838 return true;
1839}
1840
Richard Trieu55733de2011-10-28 00:41:25 +00001841template<typename Range>
1842void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1843 SourceLocation Loc,
1844 bool IsStringLocation,
1845 Range StringRange,
1846 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001847 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001848 Loc, IsStringLocation, StringRange, FixIt);
1849}
1850
1851/// \brief If the format string is not within the funcion call, emit a note
1852/// so that the function call and string are in diagnostic messages.
1853///
1854/// \param inFunctionCall if true, the format string is within the function
1855/// call and only one diagnostic message will be produced. Otherwise, an
1856/// extra note will be emitted pointing to location of the format string.
1857///
1858/// \param ArgumentExpr the expression that is passed as the format string
1859/// argument in the function call. Used for getting locations when two
1860/// diagnostics are emitted.
1861///
1862/// \param PDiag the callee should already have provided any strings for the
1863/// diagnostic message. This function only adds locations and fixits
1864/// to diagnostics.
1865///
1866/// \param Loc primary location for diagnostic. If two diagnostics are
1867/// required, one will be at Loc and a new SourceLocation will be created for
1868/// the other one.
1869///
1870/// \param IsStringLocation if true, Loc points to the format string should be
1871/// used for the note. Otherwise, Loc points to the argument list and will
1872/// be used with PDiag.
1873///
1874/// \param StringRange some or all of the string to highlight. This is
1875/// templated so it can accept either a CharSourceRange or a SourceRange.
1876///
1877/// \param Fixit optional fix it hint for the format string.
1878template<typename Range>
1879void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1880 const Expr *ArgumentExpr,
1881 PartialDiagnostic PDiag,
1882 SourceLocation Loc,
1883 bool IsStringLocation,
1884 Range StringRange,
1885 FixItHint FixIt) {
1886 if (InFunctionCall)
1887 S.Diag(Loc, PDiag) << StringRange << FixIt;
1888 else {
1889 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1890 << ArgumentExpr->getSourceRange();
1891 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1892 diag::note_format_string_defined)
1893 << StringRange << FixIt;
1894 }
1895}
1896
Ted Kremenek826a3452010-07-16 02:11:22 +00001897//===--- CHECK: Printf format string checking ------------------------------===//
1898
1899namespace {
1900class CheckPrintfHandler : public CheckFormatHandler {
1901public:
1902 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1903 const Expr *origFormatExpr, unsigned firstDataArg,
1904 unsigned numDataArgs, bool isObjCLiteral,
1905 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001906 Expr **Args, unsigned NumArgs,
1907 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001908 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1909 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001910 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001911
1912
1913 bool HandleInvalidPrintfConversionSpecifier(
1914 const analyze_printf::PrintfSpecifier &FS,
1915 const char *startSpecifier,
1916 unsigned specifierLen);
1917
1918 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1919 const char *startSpecifier,
1920 unsigned specifierLen);
1921
1922 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1923 const char *startSpecifier, unsigned specifierLen);
1924 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1925 const analyze_printf::OptionalAmount &Amt,
1926 unsigned type,
1927 const char *startSpecifier, unsigned specifierLen);
1928 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1929 const analyze_printf::OptionalFlag &flag,
1930 const char *startSpecifier, unsigned specifierLen);
1931 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1932 const analyze_printf::OptionalFlag &ignoredFlag,
1933 const analyze_printf::OptionalFlag &flag,
1934 const char *startSpecifier, unsigned specifierLen);
1935};
1936}
1937
1938bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1939 const analyze_printf::PrintfSpecifier &FS,
1940 const char *startSpecifier,
1941 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001942 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001943 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001944
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001945 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1946 getLocationOfByte(CS.getStart()),
1947 startSpecifier, specifierLen,
1948 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001949}
1950
Ted Kremenek826a3452010-07-16 02:11:22 +00001951bool CheckPrintfHandler::HandleAmount(
1952 const analyze_format_string::OptionalAmount &Amt,
1953 unsigned k, const char *startSpecifier,
1954 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001955
1956 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001957 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001958 unsigned argIndex = Amt.getArgIndex();
1959 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001960 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1961 << k,
1962 getLocationOfByte(Amt.getStart()),
1963 /*IsStringLocation*/true,
1964 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001965 // Don't do any more checking. We will just emit
1966 // spurious errors.
1967 return false;
1968 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001969
Ted Kremenek0d277352010-01-29 01:06:55 +00001970 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001971 // Although not in conformance with C99, we also allow the argument to be
1972 // an 'unsigned int' as that is a reasonably safe case. GCC also
1973 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001974 CoveredArgs.set(argIndex);
1975 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001976 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977
1978 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1979 assert(ATR.isValid());
1980
1981 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001982 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00001983 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00001984 << T << Arg->getSourceRange(),
1985 getLocationOfByte(Amt.getStart()),
1986 /*IsStringLocation*/true,
1987 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001988 // Don't do any more checking. We will just emit
1989 // spurious errors.
1990 return false;
1991 }
1992 }
1993 }
1994 return true;
1995}
Ted Kremenek0d277352010-01-29 01:06:55 +00001996
Tom Caree4ee9662010-06-17 19:00:27 +00001997void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001998 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001999 const analyze_printf::OptionalAmount &Amt,
2000 unsigned type,
2001 const char *startSpecifier,
2002 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002003 const analyze_printf::PrintfConversionSpecifier &CS =
2004 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002005
Richard Trieu55733de2011-10-28 00:41:25 +00002006 FixItHint fixit =
2007 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2008 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2009 Amt.getConstantLength()))
2010 : FixItHint();
2011
2012 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2013 << type << CS.toString(),
2014 getLocationOfByte(Amt.getStart()),
2015 /*IsStringLocation*/true,
2016 getSpecifierRange(startSpecifier, specifierLen),
2017 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002018}
2019
Ted Kremenek826a3452010-07-16 02:11:22 +00002020void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002021 const analyze_printf::OptionalFlag &flag,
2022 const char *startSpecifier,
2023 unsigned specifierLen) {
2024 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002025 const analyze_printf::PrintfConversionSpecifier &CS =
2026 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002027 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2028 << flag.toString() << CS.toString(),
2029 getLocationOfByte(flag.getPosition()),
2030 /*IsStringLocation*/true,
2031 getSpecifierRange(startSpecifier, specifierLen),
2032 FixItHint::CreateRemoval(
2033 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002034}
2035
2036void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002037 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002038 const analyze_printf::OptionalFlag &ignoredFlag,
2039 const analyze_printf::OptionalFlag &flag,
2040 const char *startSpecifier,
2041 unsigned specifierLen) {
2042 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002043 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2044 << ignoredFlag.toString() << flag.toString(),
2045 getLocationOfByte(ignoredFlag.getPosition()),
2046 /*IsStringLocation*/true,
2047 getSpecifierRange(startSpecifier, specifierLen),
2048 FixItHint::CreateRemoval(
2049 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002050}
2051
Ted Kremeneke0e53132010-01-28 23:39:18 +00002052bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002053CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002054 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002055 const char *startSpecifier,
2056 unsigned specifierLen) {
2057
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002058 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002059 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002060 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002061
Ted Kremenekbaa40062010-07-19 22:01:06 +00002062 if (FS.consumesDataArgument()) {
2063 if (atFirstArg) {
2064 atFirstArg = false;
2065 usesPositionalArgs = FS.usesPositionalArg();
2066 }
2067 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002068 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2069 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002070 return false;
2071 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002072 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002073
Ted Kremenekefaff192010-02-27 01:41:03 +00002074 // First check if the field width, precision, and conversion specifier
2075 // have matching data arguments.
2076 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2077 startSpecifier, specifierLen)) {
2078 return false;
2079 }
2080
2081 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2082 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002083 return false;
2084 }
2085
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002086 if (!CS.consumesDataArgument()) {
2087 // FIXME: Technically specifying a precision or field width here
2088 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002089 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002090 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002091
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002092 // Consume the argument.
2093 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002094 if (argIndex < NumDataArgs) {
2095 // The check to see if the argIndex is valid will come later.
2096 // We set the bit here because we may exit early from this
2097 // function if we encounter some other error.
2098 CoveredArgs.set(argIndex);
2099 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002100
2101 // Check for using an Objective-C specific conversion specifier
2102 // in a non-ObjC literal.
2103 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002104 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2105 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002106 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002107
Tom Caree4ee9662010-06-17 19:00:27 +00002108 // Check for invalid use of field width
2109 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002110 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002111 startSpecifier, specifierLen);
2112 }
2113
2114 // Check for invalid use of precision
2115 if (!FS.hasValidPrecision()) {
2116 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2117 startSpecifier, specifierLen);
2118 }
2119
2120 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002121 if (!FS.hasValidThousandsGroupingPrefix())
2122 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002123 if (!FS.hasValidLeadingZeros())
2124 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2125 if (!FS.hasValidPlusPrefix())
2126 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002127 if (!FS.hasValidSpacePrefix())
2128 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002129 if (!FS.hasValidAlternativeForm())
2130 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2131 if (!FS.hasValidLeftJustified())
2132 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2133
2134 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002135 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2136 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2137 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002138 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2139 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2140 startSpecifier, specifierLen);
2141
2142 // Check the length modifier is valid with the given conversion specifier.
2143 const LengthModifier &LM = FS.getLengthModifier();
2144 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002145 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2146 << LM.toString() << CS.toString(),
2147 getLocationOfByte(LM.getStart()),
2148 /*IsStringLocation*/true,
2149 getSpecifierRange(startSpecifier, specifierLen),
2150 FixItHint::CreateRemoval(
2151 getSpecifierRange(LM.getStart(),
2152 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002153
2154 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002155 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002156 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002157 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2158 getLocationOfByte(CS.getStart()),
2159 /*IsStringLocation*/true,
2160 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002161 // Continue checking the other format specifiers.
2162 return true;
2163 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002164
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002165 // The remaining checks depend on the data arguments.
2166 if (HasVAListArg)
2167 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002168
Ted Kremenek666a1972010-07-26 19:45:42 +00002169 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002170 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002171
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002172 // Now type check the data expression that matches the
2173 // format specifier.
2174 const Expr *Ex = getDataArg(argIndex);
Nick Lewycky687b5df2011-12-02 23:21:43 +00002175 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002176 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2177 // Check if we didn't match because of an implicit cast from a 'char'
2178 // or 'short' to an 'int'. This is done because printf is a varargs
2179 // function.
2180 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002181 if (ICE->getType() == S.Context.IntTy) {
2182 // All further checking is done on the subexpression.
2183 Ex = ICE->getSubExpr();
2184 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002185 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002186 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002187
2188 // We may be able to offer a FixItHint if it is a supported type.
2189 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002190 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002191
2192 if (success) {
2193 // Get the fix string from the fixed format specifier
2194 llvm::SmallString<128> buf;
2195 llvm::raw_svector_ostream os(buf);
2196 fixedFS.toString(os);
2197
Richard Trieu55733de2011-10-28 00:41:25 +00002198 EmitFormatDiagnostic(
2199 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002200 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002201 << Ex->getSourceRange(),
2202 getLocationOfByte(CS.getStart()),
2203 /*IsStringLocation*/true,
2204 getSpecifierRange(startSpecifier, specifierLen),
2205 FixItHint::CreateReplacement(
2206 getSpecifierRange(startSpecifier, specifierLen),
2207 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002208 }
2209 else {
2210 S.Diag(getLocationOfByte(CS.getStart()),
2211 diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002212 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002213 << getSpecifierRange(startSpecifier, specifierLen)
2214 << Ex->getSourceRange();
2215 }
2216 }
2217
Ted Kremeneke0e53132010-01-28 23:39:18 +00002218 return true;
2219}
2220
Ted Kremenek826a3452010-07-16 02:11:22 +00002221//===--- CHECK: Scanf format string checking ------------------------------===//
2222
2223namespace {
2224class CheckScanfHandler : public CheckFormatHandler {
2225public:
2226 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2227 const Expr *origFormatExpr, unsigned firstDataArg,
2228 unsigned numDataArgs, bool isObjCLiteral,
2229 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002230 Expr **Args, unsigned NumArgs,
2231 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002232 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2233 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002234 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002235
2236 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2237 const char *startSpecifier,
2238 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002239
2240 bool HandleInvalidScanfConversionSpecifier(
2241 const analyze_scanf::ScanfSpecifier &FS,
2242 const char *startSpecifier,
2243 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002244
2245 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002246};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002247}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002248
Ted Kremenekb7c21012010-07-16 18:28:03 +00002249void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2250 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002251 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2252 getLocationOfByte(end), /*IsStringLocation*/true,
2253 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002254}
2255
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002256bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2257 const analyze_scanf::ScanfSpecifier &FS,
2258 const char *startSpecifier,
2259 unsigned specifierLen) {
2260
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002261 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002262 FS.getConversionSpecifier();
2263
2264 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2265 getLocationOfByte(CS.getStart()),
2266 startSpecifier, specifierLen,
2267 CS.getStart(), CS.getLength());
2268}
2269
Ted Kremenek826a3452010-07-16 02:11:22 +00002270bool CheckScanfHandler::HandleScanfSpecifier(
2271 const analyze_scanf::ScanfSpecifier &FS,
2272 const char *startSpecifier,
2273 unsigned specifierLen) {
2274
2275 using namespace analyze_scanf;
2276 using namespace analyze_format_string;
2277
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002278 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002279
Ted Kremenekbaa40062010-07-19 22:01:06 +00002280 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2281 // be used to decide if we are using positional arguments consistently.
2282 if (FS.consumesDataArgument()) {
2283 if (atFirstArg) {
2284 atFirstArg = false;
2285 usesPositionalArgs = FS.usesPositionalArg();
2286 }
2287 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002288 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2289 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002290 return false;
2291 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002292 }
2293
2294 // Check if the field with is non-zero.
2295 const OptionalAmount &Amt = FS.getFieldWidth();
2296 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2297 if (Amt.getConstantAmount() == 0) {
2298 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2299 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002300 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2301 getLocationOfByte(Amt.getStart()),
2302 /*IsStringLocation*/true, R,
2303 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002304 }
2305 }
2306
2307 if (!FS.consumesDataArgument()) {
2308 // FIXME: Technically specifying a precision or field width here
2309 // makes no sense. Worth issuing a warning at some point.
2310 return true;
2311 }
2312
2313 // Consume the argument.
2314 unsigned argIndex = FS.getArgIndex();
2315 if (argIndex < NumDataArgs) {
2316 // The check to see if the argIndex is valid will come later.
2317 // We set the bit here because we may exit early from this
2318 // function if we encounter some other error.
2319 CoveredArgs.set(argIndex);
2320 }
2321
Ted Kremenek1e51c202010-07-20 20:04:47 +00002322 // Check the length modifier is valid with the given conversion specifier.
2323 const LengthModifier &LM = FS.getLengthModifier();
2324 if (!FS.hasValidLengthModifier()) {
2325 S.Diag(getLocationOfByte(LM.getStart()),
2326 diag::warn_format_nonsensical_length)
2327 << LM.toString() << CS.toString()
2328 << getSpecifierRange(startSpecifier, specifierLen)
2329 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2330 LM.getLength()));
2331 }
2332
Ted Kremenek826a3452010-07-16 02:11:22 +00002333 // The remaining checks depend on the data arguments.
2334 if (HasVAListArg)
2335 return true;
2336
Ted Kremenek666a1972010-07-26 19:45:42 +00002337 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002338 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002339
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002340 // Check that the argument type matches the format specifier.
2341 const Expr *Ex = getDataArg(argIndex);
2342 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2343 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2344 ScanfSpecifier fixedFS = FS;
2345 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2346
2347 if (success) {
2348 // Get the fix string from the fixed format specifier.
2349 llvm::SmallString<128> buf;
2350 llvm::raw_svector_ostream os(buf);
2351 fixedFS.toString(os);
2352
2353 EmitFormatDiagnostic(
2354 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2355 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2356 << Ex->getSourceRange(),
2357 getLocationOfByte(CS.getStart()),
2358 /*IsStringLocation*/true,
2359 getSpecifierRange(startSpecifier, specifierLen),
2360 FixItHint::CreateReplacement(
2361 getSpecifierRange(startSpecifier, specifierLen),
2362 os.str()));
2363 } else {
2364 S.Diag(getLocationOfByte(CS.getStart()),
2365 diag::warn_printf_conversion_argument_type_mismatch)
2366 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2367 << getSpecifierRange(startSpecifier, specifierLen)
2368 << Ex->getSourceRange();
2369 }
2370 }
2371
Ted Kremenek826a3452010-07-16 02:11:22 +00002372 return true;
2373}
2374
2375void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002376 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002377 Expr **Args, unsigned NumArgs,
2378 bool HasVAListArg, unsigned format_idx,
2379 unsigned firstDataArg, bool isPrintf,
2380 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002381
Ted Kremeneke0e53132010-01-28 23:39:18 +00002382 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002383 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002384 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002385 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002386 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2387 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002388 return;
2389 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002390
Ted Kremeneke0e53132010-01-28 23:39:18 +00002391 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002393 const char *Str = StrRef.data();
2394 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002395 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002396
Ted Kremeneke0e53132010-01-28 23:39:18 +00002397 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002398 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002399 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002400 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002401 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2402 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002403 return;
2404 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002405
2406 if (isPrintf) {
2407 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002408 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002409 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002410 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002411
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002412 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2413 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002414 H.DoneProcessing();
2415 }
2416 else {
2417 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002418 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002419 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002420 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002421
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002422 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2423 getLangOptions()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002424 H.DoneProcessing();
2425 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002426}
2427
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002428//===--- CHECK: Standard memory functions ---------------------------------===//
2429
Douglas Gregor2a053a32011-05-03 20:05:22 +00002430/// \brief Determine whether the given type is a dynamic class type (e.g.,
2431/// whether it has a vtable).
2432static bool isDynamicClassType(QualType T) {
2433 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2434 if (CXXRecordDecl *Definition = Record->getDefinition())
2435 if (Definition->isDynamicClass())
2436 return true;
2437
2438 return false;
2439}
2440
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002441/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002442/// otherwise returns NULL.
2443static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002444 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002445 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2446 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2447 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002448
Chandler Carruth000d4282011-06-16 09:09:40 +00002449 return 0;
2450}
2451
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002452/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002453static QualType getSizeOfArgType(const Expr* E) {
2454 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2455 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2456 if (SizeOf->getKind() == clang::UETT_SizeOf)
2457 return SizeOf->getTypeOfArgument();
2458
2459 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002460}
2461
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002462/// \brief Check for dangerous or invalid arguments to memset().
2463///
Chandler Carruth929f0132011-06-03 06:23:57 +00002464/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002465/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2466/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002467///
2468/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002469void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002470 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002471 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002472 assert(BId != 0);
2473
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002474 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002475 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002476 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002477 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002478 return;
2479
Anna Zaks0a151a12012-01-17 00:37:07 +00002480 unsigned LastArg = (BId == Builtin::BImemset ||
2481 BId == Builtin::BIstrndup ? 1 : 2);
2482 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002483 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002484
2485 // We have special checking when the length is a sizeof expression.
2486 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2487 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2488 llvm::FoldingSetNodeID SizeOfArgID;
2489
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002490 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2491 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002492 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002493
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002494 QualType DestTy = Dest->getType();
2495 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2496 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002497
Chandler Carruth000d4282011-06-16 09:09:40 +00002498 // Never warn about void type pointers. This can be used to suppress
2499 // false positives.
2500 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002501 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002502
Chandler Carruth000d4282011-06-16 09:09:40 +00002503 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2504 // actually comparing the expressions for equality. Because computing the
2505 // expression IDs can be expensive, we only do this if the diagnostic is
2506 // enabled.
2507 if (SizeOfArg &&
2508 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2509 SizeOfArg->getExprLoc())) {
2510 // We only compute IDs for expressions if the warning is enabled, and
2511 // cache the sizeof arg's ID.
2512 if (SizeOfArgID == llvm::FoldingSetNodeID())
2513 SizeOfArg->Profile(SizeOfArgID, Context, true);
2514 llvm::FoldingSetNodeID DestID;
2515 Dest->Profile(DestID, Context, true);
2516 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002517 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2518 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002519 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2520 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2521 if (UnaryOp->getOpcode() == UO_AddrOf)
2522 ActionIdx = 1; // If its an address-of operator, just remove it.
2523 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2524 ActionIdx = 2; // If the pointee's size is sizeof(char),
2525 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002526 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002527 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002528 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2529 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002530 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002531 << Dest->getSourceRange()
2532 << SizeOfArg->getSourceRange());
2533 break;
2534 }
2535 }
2536
2537 // Also check for cases where the sizeof argument is the exact same
2538 // type as the memory argument, and where it points to a user-defined
2539 // record type.
2540 if (SizeOfArgTy != QualType()) {
2541 if (PointeeTy->isRecordType() &&
2542 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2543 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2544 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2545 << FnName << SizeOfArgTy << ArgIdx
2546 << PointeeTy << Dest->getSourceRange()
2547 << LenExpr->getSourceRange());
2548 break;
2549 }
Nico Webere4a1c642011-06-14 16:14:58 +00002550 }
2551
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002552 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002553 if (isDynamicClassType(PointeeTy)) {
2554
2555 unsigned OperationType = 0;
2556 // "overwritten" if we're warning about the destination for any call
2557 // but memcmp; otherwise a verb appropriate to the call.
2558 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2559 if (BId == Builtin::BImemcpy)
2560 OperationType = 1;
2561 else if(BId == Builtin::BImemmove)
2562 OperationType = 2;
2563 else if (BId == Builtin::BImemcmp)
2564 OperationType = 3;
2565 }
2566
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002567 DiagRuntimeBehavior(
2568 Dest->getExprLoc(), Dest,
2569 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002570 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002571 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002572 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002573 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002574 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2575 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002576 DiagRuntimeBehavior(
2577 Dest->getExprLoc(), Dest,
2578 PDiag(diag::warn_arc_object_memaccess)
2579 << ArgIdx << FnName << PointeeTy
2580 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002581 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002582 continue;
John McCallf85e1932011-06-15 23:02:42 +00002583
2584 DiagRuntimeBehavior(
2585 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002586 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002587 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2588 break;
2589 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002590 }
2591}
2592
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002593// A little helper routine: ignore addition and subtraction of integer literals.
2594// This intentionally does not ignore all integer constant expressions because
2595// we don't want to remove sizeof().
2596static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2597 Ex = Ex->IgnoreParenCasts();
2598
2599 for (;;) {
2600 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2601 if (!BO || !BO->isAdditiveOp())
2602 break;
2603
2604 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2605 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2606
2607 if (isa<IntegerLiteral>(RHS))
2608 Ex = LHS;
2609 else if (isa<IntegerLiteral>(LHS))
2610 Ex = RHS;
2611 else
2612 break;
2613 }
2614
2615 return Ex;
2616}
2617
2618// Warn if the user has made the 'size' argument to strlcpy or strlcat
2619// be the size of the source, instead of the destination.
2620void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2621 IdentifierInfo *FnName) {
2622
2623 // Don't crash if the user has the wrong number of arguments
2624 if (Call->getNumArgs() != 3)
2625 return;
2626
2627 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2628 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2629 const Expr *CompareWithSrc = NULL;
2630
2631 // Look for 'strlcpy(dst, x, sizeof(x))'
2632 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2633 CompareWithSrc = Ex;
2634 else {
2635 // Look for 'strlcpy(dst, x, strlen(x))'
2636 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002637 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002638 && SizeCall->getNumArgs() == 1)
2639 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2640 }
2641 }
2642
2643 if (!CompareWithSrc)
2644 return;
2645
2646 // Determine if the argument to sizeof/strlen is equal to the source
2647 // argument. In principle there's all kinds of things you could do
2648 // here, for instance creating an == expression and evaluating it with
2649 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2650 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2651 if (!SrcArgDRE)
2652 return;
2653
2654 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2655 if (!CompareWithSrcDRE ||
2656 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2657 return;
2658
2659 const Expr *OriginalSizeArg = Call->getArg(2);
2660 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2661 << OriginalSizeArg->getSourceRange() << FnName;
2662
2663 // Output a FIXIT hint if the destination is an array (rather than a
2664 // pointer to an array). This could be enhanced to handle some
2665 // pointers if we know the actual size, like if DstArg is 'array+2'
2666 // we could say 'sizeof(array)-2'.
2667 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002668 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002669
Ted Kremenek8f746222011-08-18 22:48:41 +00002670 // Only handle constant-sized or VLAs, but not flexible members.
2671 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2672 // Only issue the FIXIT for arrays of size > 1.
2673 if (CAT->getSize().getSExtValue() <= 1)
2674 return;
2675 } else if (!DstArgTy->isVariableArrayType()) {
2676 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002677 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002678
2679 llvm::SmallString<128> sizeString;
2680 llvm::raw_svector_ostream OS(sizeString);
2681 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002682 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002683 OS << ")";
2684
2685 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2686 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2687 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002688}
2689
Ted Kremenek06de2762007-08-17 16:46:58 +00002690//===--- CHECK: Return Address of Stack Variable --------------------------===//
2691
Chris Lattner5f9e2722011-07-23 10:55:15 +00002692static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2693static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002694
2695/// CheckReturnStackAddr - Check if a return statement returns the address
2696/// of a stack variable.
2697void
2698Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2699 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002701 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002702 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002703
2704 // Perform checking for returned stack addresses, local blocks,
2705 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002706 if (lhsType->isPointerType() ||
2707 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002708 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002709 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002710 stackE = EvalVal(RetValExp, refVars);
2711 }
2712
2713 if (stackE == 0)
2714 return; // Nothing suspicious was found.
2715
2716 SourceLocation diagLoc;
2717 SourceRange diagRange;
2718 if (refVars.empty()) {
2719 diagLoc = stackE->getLocStart();
2720 diagRange = stackE->getSourceRange();
2721 } else {
2722 // We followed through a reference variable. 'stackE' contains the
2723 // problematic expression but we will warn at the return statement pointing
2724 // at the reference variable. We will later display the "trail" of
2725 // reference variables using notes.
2726 diagLoc = refVars[0]->getLocStart();
2727 diagRange = refVars[0]->getSourceRange();
2728 }
2729
2730 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2731 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2732 : diag::warn_ret_stack_addr)
2733 << DR->getDecl()->getDeclName() << diagRange;
2734 } else if (isa<BlockExpr>(stackE)) { // local block.
2735 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2736 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2737 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2738 } else { // local temporary.
2739 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2740 : diag::warn_ret_local_temp_addr)
2741 << diagRange;
2742 }
2743
2744 // Display the "trail" of reference variables that we followed until we
2745 // found the problematic expression using notes.
2746 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2747 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2748 // If this var binds to another reference var, show the range of the next
2749 // var, otherwise the var binds to the problematic expression, in which case
2750 // show the range of the expression.
2751 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2752 : stackE->getSourceRange();
2753 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2754 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002755 }
2756}
2757
2758/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2759/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002760/// to a location on the stack, a local block, an address of a label, or a
2761/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002762/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002763/// encounter a subexpression that (1) clearly does not lead to one of the
2764/// above problematic expressions (2) is something we cannot determine leads to
2765/// a problematic expression based on such local checking.
2766///
2767/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2768/// the expression that they point to. Such variables are added to the
2769/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002770///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002771/// EvalAddr processes expressions that are pointers that are used as
2772/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002773/// At the base case of the recursion is a check for the above problematic
2774/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002775///
2776/// This implementation handles:
2777///
2778/// * pointer-to-pointer casts
2779/// * implicit conversions from array references to pointers
2780/// * taking the address of fields
2781/// * arbitrary interplay between "&" and "*" operators
2782/// * pointer arithmetic from an address of a stack variable
2783/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002784static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002785 if (E->isTypeDependent())
2786 return NULL;
2787
Ted Kremenek06de2762007-08-17 16:46:58 +00002788 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002789 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002790 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002791 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002792 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Peter Collingbournef111d932011-04-15 00:35:48 +00002794 E = E->IgnoreParens();
2795
Ted Kremenek06de2762007-08-17 16:46:58 +00002796 // Our "symbolic interpreter" is just a dispatch off the currently
2797 // viewed AST node. We then recursively traverse the AST by calling
2798 // EvalAddr and EvalVal appropriately.
2799 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002800 case Stmt::DeclRefExprClass: {
2801 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2802
2803 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2804 // If this is a reference variable, follow through to the expression that
2805 // it points to.
2806 if (V->hasLocalStorage() &&
2807 V->getType()->isReferenceType() && V->hasInit()) {
2808 // Add the reference variable to the "trail".
2809 refVars.push_back(DR);
2810 return EvalAddr(V->getInit(), refVars);
2811 }
2812
2813 return NULL;
2814 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002815
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002816 case Stmt::UnaryOperatorClass: {
2817 // The only unary operator that make sense to handle here
2818 // is AddrOf. All others don't make sense as pointers.
2819 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002820
John McCall2de56d12010-08-25 11:45:40 +00002821 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002822 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002823 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002824 return NULL;
2825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002827 case Stmt::BinaryOperatorClass: {
2828 // Handle pointer arithmetic. All other binary operators are not valid
2829 // in this context.
2830 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002831 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002832
John McCall2de56d12010-08-25 11:45:40 +00002833 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002834 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002836 Expr *Base = B->getLHS();
2837
2838 // Determine which argument is the real pointer base. It could be
2839 // the RHS argument instead of the LHS.
2840 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002842 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002843 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002844 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002845
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002846 // For conditional operators we need to see if either the LHS or RHS are
2847 // valid DeclRefExpr*s. If one of them is valid, we return it.
2848 case Stmt::ConditionalOperatorClass: {
2849 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002851 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002852 if (Expr *lhsExpr = C->getLHS()) {
2853 // In C++, we can have a throw-expression, which has 'void' type.
2854 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002855 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002856 return LHS;
2857 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002858
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002859 // In C++, we can have a throw-expression, which has 'void' type.
2860 if (C->getRHS()->getType()->isVoidType())
2861 return NULL;
2862
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002863 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002864 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002865
2866 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002867 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002868 return E; // local block.
2869 return NULL;
2870
2871 case Stmt::AddrLabelExprClass:
2872 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002873
John McCall80ee6e82011-11-10 05:35:25 +00002874 case Stmt::ExprWithCleanupsClass:
2875 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2876
Ted Kremenek54b52742008-08-07 00:49:01 +00002877 // For casts, we need to handle conversions from arrays to
2878 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002879 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002880 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002881 case Stmt::CXXFunctionalCastExprClass:
2882 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002883 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002884 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Steve Naroffdd972f22008-09-05 22:11:13 +00002886 if (SubExpr->getType()->isPointerType() ||
2887 SubExpr->getType()->isBlockPointerType() ||
2888 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002889 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002890 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002891 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002892 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002893 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002894 }
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002896 // C++ casts. For dynamic casts, static casts, and const casts, we
2897 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002898 // through the cast. In the case the dynamic cast doesn't fail (and
2899 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002900 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002901 // FIXME: The comment about is wrong; we're not always converting
2902 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002903 // handle references to objects.
2904 case Stmt::CXXStaticCastExprClass:
2905 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002906 case Stmt::CXXConstCastExprClass:
2907 case Stmt::CXXReinterpretCastExprClass: {
2908 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002909 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002910 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002911 else
2912 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Douglas Gregor03e80032011-06-21 17:03:29 +00002915 case Stmt::MaterializeTemporaryExprClass:
2916 if (Expr *Result = EvalAddr(
2917 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2918 refVars))
2919 return Result;
2920
2921 return E;
2922
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002923 // Everything else: we simply don't reason about them.
2924 default:
2925 return NULL;
2926 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002927}
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Ted Kremenek06de2762007-08-17 16:46:58 +00002929
2930/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2931/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002932static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002933do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002934 // We should only be called for evaluating non-pointer expressions, or
2935 // expressions with a pointer type that are not used as references but instead
2936 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Ted Kremenek06de2762007-08-17 16:46:58 +00002938 // Our "symbolic interpreter" is just a dispatch off the currently
2939 // viewed AST node. We then recursively traverse the AST by calling
2940 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002941
2942 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002943 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002944 case Stmt::ImplicitCastExprClass: {
2945 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002946 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002947 E = IE->getSubExpr();
2948 continue;
2949 }
2950 return NULL;
2951 }
2952
John McCall80ee6e82011-11-10 05:35:25 +00002953 case Stmt::ExprWithCleanupsClass:
2954 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2955
Douglas Gregora2813ce2009-10-23 18:54:35 +00002956 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002957 // When we hit a DeclRefExpr we are looking at code that refers to a
2958 // variable's name. If it's not a reference variable we check if it has
2959 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002960 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Ted Kremenek06de2762007-08-17 16:46:58 +00002962 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002963 if (V->hasLocalStorage()) {
2964 if (!V->getType()->isReferenceType())
2965 return DR;
2966
2967 // Reference variable, follow through to the expression that
2968 // it points to.
2969 if (V->hasInit()) {
2970 // Add the reference variable to the "trail".
2971 refVars.push_back(DR);
2972 return EvalVal(V->getInit(), refVars);
2973 }
2974 }
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Ted Kremenek06de2762007-08-17 16:46:58 +00002976 return NULL;
2977 }
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Ted Kremenek06de2762007-08-17 16:46:58 +00002979 case Stmt::UnaryOperatorClass: {
2980 // The only unary operator that make sense to handle here
2981 // is Deref. All others don't resolve to a "name." This includes
2982 // handling all sorts of rvalues passed to a unary operator.
2983 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002984
John McCall2de56d12010-08-25 11:45:40 +00002985 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002986 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002987
2988 return NULL;
2989 }
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Ted Kremenek06de2762007-08-17 16:46:58 +00002991 case Stmt::ArraySubscriptExprClass: {
2992 // Array subscripts are potential references to data on the stack. We
2993 // retrieve the DeclRefExpr* for the array variable if it indeed
2994 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002995 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002996 }
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Ted Kremenek06de2762007-08-17 16:46:58 +00002998 case Stmt::ConditionalOperatorClass: {
2999 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003000 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003001 ConditionalOperator *C = cast<ConditionalOperator>(E);
3002
Anders Carlsson39073232007-11-30 19:04:31 +00003003 // Handle the GNU extension for missing LHS.
3004 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003005 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003006 return LHS;
3007
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003008 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Ted Kremenek06de2762007-08-17 16:46:58 +00003011 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003012 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003013 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Ted Kremenek06de2762007-08-17 16:46:58 +00003015 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003016 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003017 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003018
3019 // Check whether the member type is itself a reference, in which case
3020 // we're not going to refer to the member, but to what the member refers to.
3021 if (M->getMemberDecl()->getType()->isReferenceType())
3022 return NULL;
3023
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003024 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Douglas Gregor03e80032011-06-21 17:03:29 +00003027 case Stmt::MaterializeTemporaryExprClass:
3028 if (Expr *Result = EvalVal(
3029 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3030 refVars))
3031 return Result;
3032
3033 return E;
3034
Ted Kremenek06de2762007-08-17 16:46:58 +00003035 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003036 // Check that we don't return or take the address of a reference to a
3037 // temporary. This is only useful in C++.
3038 if (!E->isTypeDependent() && E->isRValue())
3039 return E;
3040
3041 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003042 return NULL;
3043 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003044} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003045}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003046
3047//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3048
3049/// Check for comparisons of floating point operands using != and ==.
3050/// Issue a warning if these are no self-comparisons, as they are not likely
3051/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003052void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003053 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Richard Trieudd225092011-09-15 21:56:47 +00003055 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3056 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003057
3058 // Special case: check for x == x (which is OK).
3059 // Do not emit warnings for such cases.
3060 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3061 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3062 if (DRL->getDecl() == DRR->getDecl())
3063 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003064
3065
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003066 // Special case: check for comparisons against literals that can be exactly
3067 // represented by APFloat. In such cases, do not emit a warning. This
3068 // is a heuristic: often comparison against such literals are used to
3069 // detect if a value in a variable has not changed. This clearly can
3070 // lead to false negatives.
3071 if (EmitWarning) {
3072 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3073 if (FLL->isExact())
3074 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003075 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003076 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3077 if (FLR->isExact())
3078 EmitWarning = false;
3079 }
3080 }
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003082 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003083 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003084 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003085 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003086 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Sebastian Redl0eb23302009-01-19 00:08:26 +00003088 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003089 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003090 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003091 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003093 // Emit the diagnostic.
3094 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003095 Diag(Loc, diag::warn_floatingpoint_eq)
3096 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003097}
John McCallba26e582010-01-04 23:21:16 +00003098
John McCallf2370c92010-01-06 05:24:50 +00003099//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3100//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003101
John McCallf2370c92010-01-06 05:24:50 +00003102namespace {
John McCallba26e582010-01-04 23:21:16 +00003103
John McCallf2370c92010-01-06 05:24:50 +00003104/// Structure recording the 'active' range of an integer-valued
3105/// expression.
3106struct IntRange {
3107 /// The number of bits active in the int.
3108 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003109
John McCallf2370c92010-01-06 05:24:50 +00003110 /// True if the int is known not to have negative values.
3111 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003112
John McCallf2370c92010-01-06 05:24:50 +00003113 IntRange(unsigned Width, bool NonNegative)
3114 : Width(Width), NonNegative(NonNegative)
3115 {}
John McCallba26e582010-01-04 23:21:16 +00003116
John McCall1844a6e2010-11-10 23:38:19 +00003117 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003118 static IntRange forBoolType() {
3119 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003120 }
3121
John McCall1844a6e2010-11-10 23:38:19 +00003122 /// Returns the range of an opaque value of the given integral type.
3123 static IntRange forValueOfType(ASTContext &C, QualType T) {
3124 return forValueOfCanonicalType(C,
3125 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003126 }
3127
John McCall1844a6e2010-11-10 23:38:19 +00003128 /// Returns the range of an opaque value of a canonical integral type.
3129 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003130 assert(T->isCanonicalUnqualified());
3131
3132 if (const VectorType *VT = dyn_cast<VectorType>(T))
3133 T = VT->getElementType().getTypePtr();
3134 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3135 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003136
John McCall091f23f2010-11-09 22:22:12 +00003137 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003138 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3139 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003140 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003141 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3142
John McCall323ed742010-05-06 08:58:33 +00003143 unsigned NumPositive = Enum->getNumPositiveBits();
3144 unsigned NumNegative = Enum->getNumNegativeBits();
3145
3146 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3147 }
John McCallf2370c92010-01-06 05:24:50 +00003148
3149 const BuiltinType *BT = cast<BuiltinType>(T);
3150 assert(BT->isInteger());
3151
3152 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3153 }
3154
John McCall1844a6e2010-11-10 23:38:19 +00003155 /// Returns the "target" range of a canonical integral type, i.e.
3156 /// the range of values expressible in the type.
3157 ///
3158 /// This matches forValueOfCanonicalType except that enums have the
3159 /// full range of their type, not the range of their enumerators.
3160 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3161 assert(T->isCanonicalUnqualified());
3162
3163 if (const VectorType *VT = dyn_cast<VectorType>(T))
3164 T = VT->getElementType().getTypePtr();
3165 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3166 T = CT->getElementType().getTypePtr();
3167 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003168 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003169
3170 const BuiltinType *BT = cast<BuiltinType>(T);
3171 assert(BT->isInteger());
3172
3173 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3174 }
3175
3176 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003177 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003178 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003179 L.NonNegative && R.NonNegative);
3180 }
3181
John McCall1844a6e2010-11-10 23:38:19 +00003182 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003183 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003184 return IntRange(std::min(L.Width, R.Width),
3185 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003186 }
3187};
3188
3189IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3190 if (value.isSigned() && value.isNegative())
3191 return IntRange(value.getMinSignedBits(), false);
3192
3193 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003194 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003195
3196 // isNonNegative() just checks the sign bit without considering
3197 // signedness.
3198 return IntRange(value.getActiveBits(), true);
3199}
3200
John McCall0acc3112010-01-06 22:57:21 +00003201IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003202 unsigned MaxWidth) {
3203 if (result.isInt())
3204 return GetValueRange(C, result.getInt(), MaxWidth);
3205
3206 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003207 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3208 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3209 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3210 R = IntRange::join(R, El);
3211 }
John McCallf2370c92010-01-06 05:24:50 +00003212 return R;
3213 }
3214
3215 if (result.isComplexInt()) {
3216 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3217 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3218 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003219 }
3220
3221 // This can happen with lossless casts to intptr_t of "based" lvalues.
3222 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003223 // FIXME: The only reason we need to pass the type in here is to get
3224 // the sign right on this one case. It would be nice if APValue
3225 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003226 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003227 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003228}
John McCallf2370c92010-01-06 05:24:50 +00003229
3230/// Pseudo-evaluate the given integer expression, estimating the
3231/// range of values it might take.
3232///
3233/// \param MaxWidth - the width to which the value will be truncated
3234IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3235 E = E->IgnoreParens();
3236
3237 // Try a full evaluation first.
3238 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003239 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003240 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003241
3242 // I think we only want to look through implicit casts here; if the
3243 // user has an explicit widening cast, we should treat the value as
3244 // being of the new, wider type.
3245 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003246 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003247 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3248
John McCall1844a6e2010-11-10 23:38:19 +00003249 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003250
John McCall2de56d12010-08-25 11:45:40 +00003251 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003252
John McCallf2370c92010-01-06 05:24:50 +00003253 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003254 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003255 return OutputTypeRange;
3256
3257 IntRange SubRange
3258 = GetExprRange(C, CE->getSubExpr(),
3259 std::min(MaxWidth, OutputTypeRange.Width));
3260
3261 // Bail out if the subexpr's range is as wide as the cast type.
3262 if (SubRange.Width >= OutputTypeRange.Width)
3263 return OutputTypeRange;
3264
3265 // Otherwise, we take the smaller width, and we're non-negative if
3266 // either the output type or the subexpr is.
3267 return IntRange(SubRange.Width,
3268 SubRange.NonNegative || OutputTypeRange.NonNegative);
3269 }
3270
3271 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3272 // If we can fold the condition, just take that operand.
3273 bool CondResult;
3274 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3275 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3276 : CO->getFalseExpr(),
3277 MaxWidth);
3278
3279 // Otherwise, conservatively merge.
3280 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3281 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3282 return IntRange::join(L, R);
3283 }
3284
3285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3286 switch (BO->getOpcode()) {
3287
3288 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003289 case BO_LAnd:
3290 case BO_LOr:
3291 case BO_LT:
3292 case BO_GT:
3293 case BO_LE:
3294 case BO_GE:
3295 case BO_EQ:
3296 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003297 return IntRange::forBoolType();
3298
John McCall862ff872011-07-13 06:35:24 +00003299 // The type of the assignments is the type of the LHS, so the RHS
3300 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003301 case BO_MulAssign:
3302 case BO_DivAssign:
3303 case BO_RemAssign:
3304 case BO_AddAssign:
3305 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003306 case BO_XorAssign:
3307 case BO_OrAssign:
3308 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003309 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003310
John McCall862ff872011-07-13 06:35:24 +00003311 // Simple assignments just pass through the RHS, which will have
3312 // been coerced to the LHS type.
3313 case BO_Assign:
3314 // TODO: bitfields?
3315 return GetExprRange(C, BO->getRHS(), MaxWidth);
3316
John McCallf2370c92010-01-06 05:24:50 +00003317 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003318 case BO_PtrMemD:
3319 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003320 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003321
John McCall60fad452010-01-06 22:07:33 +00003322 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003323 case BO_And:
3324 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003325 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3326 GetExprRange(C, BO->getRHS(), MaxWidth));
3327
John McCallf2370c92010-01-06 05:24:50 +00003328 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003329 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003330 // ...except that we want to treat '1 << (blah)' as logically
3331 // positive. It's an important idiom.
3332 if (IntegerLiteral *I
3333 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3334 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003335 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003336 return IntRange(R.Width, /*NonNegative*/ true);
3337 }
3338 }
3339 // fallthrough
3340
John McCall2de56d12010-08-25 11:45:40 +00003341 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003342 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003343
John McCall60fad452010-01-06 22:07:33 +00003344 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003345 case BO_Shr:
3346 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003347 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3348
3349 // If the shift amount is a positive constant, drop the width by
3350 // that much.
3351 llvm::APSInt shift;
3352 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3353 shift.isNonNegative()) {
3354 unsigned zext = shift.getZExtValue();
3355 if (zext >= L.Width)
3356 L.Width = (L.NonNegative ? 0 : 1);
3357 else
3358 L.Width -= zext;
3359 }
3360
3361 return L;
3362 }
3363
3364 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003365 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003366 return GetExprRange(C, BO->getRHS(), MaxWidth);
3367
John McCall60fad452010-01-06 22:07:33 +00003368 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003369 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003370 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003371 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003372 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003373
John McCall00fe7612011-07-14 22:39:48 +00003374 // The width of a division result is mostly determined by the size
3375 // of the LHS.
3376 case BO_Div: {
3377 // Don't 'pre-truncate' the operands.
3378 unsigned opWidth = C.getIntWidth(E->getType());
3379 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3380
3381 // If the divisor is constant, use that.
3382 llvm::APSInt divisor;
3383 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3384 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3385 if (log2 >= L.Width)
3386 L.Width = (L.NonNegative ? 0 : 1);
3387 else
3388 L.Width = std::min(L.Width - log2, MaxWidth);
3389 return L;
3390 }
3391
3392 // Otherwise, just use the LHS's width.
3393 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3394 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3395 }
3396
3397 // The result of a remainder can't be larger than the result of
3398 // either side.
3399 case BO_Rem: {
3400 // Don't 'pre-truncate' the operands.
3401 unsigned opWidth = C.getIntWidth(E->getType());
3402 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3403 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3404
3405 IntRange meet = IntRange::meet(L, R);
3406 meet.Width = std::min(meet.Width, MaxWidth);
3407 return meet;
3408 }
3409
3410 // The default behavior is okay for these.
3411 case BO_Mul:
3412 case BO_Add:
3413 case BO_Xor:
3414 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003415 break;
3416 }
3417
John McCall00fe7612011-07-14 22:39:48 +00003418 // The default case is to treat the operation as if it were closed
3419 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003420 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3421 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3422 return IntRange::join(L, R);
3423 }
3424
3425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3426 switch (UO->getOpcode()) {
3427 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003428 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003429 return IntRange::forBoolType();
3430
3431 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003432 case UO_Deref:
3433 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003434 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003435
3436 default:
3437 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3438 }
3439 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003440
3441 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003442 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003443 }
John McCallf2370c92010-01-06 05:24:50 +00003444
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003445 if (FieldDecl *BitField = E->getBitField())
3446 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003447 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003448
John McCall1844a6e2010-11-10 23:38:19 +00003449 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003450}
John McCall51313c32010-01-04 23:31:57 +00003451
John McCall323ed742010-05-06 08:58:33 +00003452IntRange GetExprRange(ASTContext &C, Expr *E) {
3453 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3454}
3455
John McCall51313c32010-01-04 23:31:57 +00003456/// Checks whether the given value, which currently has the given
3457/// source semantics, has the same value when coerced through the
3458/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003459bool IsSameFloatAfterCast(const llvm::APFloat &value,
3460 const llvm::fltSemantics &Src,
3461 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003462 llvm::APFloat truncated = value;
3463
3464 bool ignored;
3465 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3466 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3467
3468 return truncated.bitwiseIsEqual(value);
3469}
3470
3471/// Checks whether the given value, which currently has the given
3472/// source semantics, has the same value when coerced through the
3473/// target semantics.
3474///
3475/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003476bool IsSameFloatAfterCast(const APValue &value,
3477 const llvm::fltSemantics &Src,
3478 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003479 if (value.isFloat())
3480 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3481
3482 if (value.isVector()) {
3483 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3484 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3485 return false;
3486 return true;
3487 }
3488
3489 assert(value.isComplexFloat());
3490 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3491 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3492}
3493
John McCallb4eb64d2010-10-08 02:01:28 +00003494void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003495
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003496static bool IsZero(Sema &S, Expr *E) {
3497 // Suppress cases where we are comparing against an enum constant.
3498 if (const DeclRefExpr *DR =
3499 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3500 if (isa<EnumConstantDecl>(DR->getDecl()))
3501 return false;
3502
3503 // Suppress cases where the '0' value is expanded from a macro.
3504 if (E->getLocStart().isMacroID())
3505 return false;
3506
John McCall323ed742010-05-06 08:58:33 +00003507 llvm::APSInt Value;
3508 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3509}
3510
John McCall372e1032010-10-06 00:25:24 +00003511static bool HasEnumType(Expr *E) {
3512 // Strip off implicit integral promotions.
3513 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003514 if (ICE->getCastKind() != CK_IntegralCast &&
3515 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003516 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003517 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003518 }
3519
3520 return E->getType()->isEnumeralType();
3521}
3522
John McCall323ed742010-05-06 08:58:33 +00003523void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003524 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003525 if (E->isValueDependent())
3526 return;
3527
John McCall2de56d12010-08-25 11:45:40 +00003528 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003529 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003530 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003531 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003532 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003533 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003534 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003535 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003536 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003537 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003538 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003539 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003540 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003541 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003542 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003543 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3544 }
3545}
3546
3547/// Analyze the operands of the given comparison. Implements the
3548/// fallback case from AnalyzeComparison.
3549void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003550 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3551 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003552}
John McCall51313c32010-01-04 23:31:57 +00003553
John McCallba26e582010-01-04 23:21:16 +00003554/// \brief Implements -Wsign-compare.
3555///
Richard Trieudd225092011-09-15 21:56:47 +00003556/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003557void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3558 // The type the comparison is being performed in.
3559 QualType T = E->getLHS()->getType();
3560 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3561 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003562
John McCall323ed742010-05-06 08:58:33 +00003563 // We don't do anything special if this isn't an unsigned integral
3564 // comparison: we're only interested in integral comparisons, and
3565 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003566 //
3567 // We also don't care about value-dependent expressions or expressions
3568 // whose result is a constant.
3569 if (!T->hasUnsignedIntegerRepresentation()
3570 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003571 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003572
Richard Trieudd225092011-09-15 21:56:47 +00003573 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3574 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003575
John McCall323ed742010-05-06 08:58:33 +00003576 // Check to see if one of the (unmodified) operands is of different
3577 // signedness.
3578 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003579 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3580 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003581 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003582 signedOperand = LHS;
3583 unsignedOperand = RHS;
3584 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3585 signedOperand = RHS;
3586 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003587 } else {
John McCall323ed742010-05-06 08:58:33 +00003588 CheckTrivialUnsignedComparison(S, E);
3589 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003590 }
3591
John McCall323ed742010-05-06 08:58:33 +00003592 // Otherwise, calculate the effective range of the signed operand.
3593 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003594
John McCall323ed742010-05-06 08:58:33 +00003595 // Go ahead and analyze implicit conversions in the operands. Note
3596 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003597 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3598 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003599
John McCall323ed742010-05-06 08:58:33 +00003600 // If the signed range is non-negative, -Wsign-compare won't fire,
3601 // but we should still check for comparisons which are always true
3602 // or false.
3603 if (signedRange.NonNegative)
3604 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003605
3606 // For (in)equality comparisons, if the unsigned operand is a
3607 // constant which cannot collide with a overflowed signed operand,
3608 // then reinterpreting the signed operand as unsigned will not
3609 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003610 if (E->isEqualityOp()) {
3611 unsigned comparisonWidth = S.Context.getIntWidth(T);
3612 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003613
John McCall323ed742010-05-06 08:58:33 +00003614 // We should never be unable to prove that the unsigned operand is
3615 // non-negative.
3616 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3617
3618 if (unsignedRange.Width < comparisonWidth)
3619 return;
3620 }
3621
3622 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003623 << LHS->getType() << RHS->getType()
3624 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003625}
3626
John McCall15d7d122010-11-11 03:21:53 +00003627/// Analyzes an attempt to assign the given value to a bitfield.
3628///
3629/// Returns true if there was something fishy about the attempt.
3630bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3631 SourceLocation InitLoc) {
3632 assert(Bitfield->isBitField());
3633 if (Bitfield->isInvalidDecl())
3634 return false;
3635
John McCall91b60142010-11-11 05:33:51 +00003636 // White-list bool bitfields.
3637 if (Bitfield->getType()->isBooleanType())
3638 return false;
3639
Douglas Gregor46ff3032011-02-04 13:09:01 +00003640 // Ignore value- or type-dependent expressions.
3641 if (Bitfield->getBitWidth()->isValueDependent() ||
3642 Bitfield->getBitWidth()->isTypeDependent() ||
3643 Init->isValueDependent() ||
3644 Init->isTypeDependent())
3645 return false;
3646
John McCall15d7d122010-11-11 03:21:53 +00003647 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3648
Richard Smith80d4b552011-12-28 19:48:30 +00003649 llvm::APSInt Value;
3650 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003651 return false;
3652
John McCall15d7d122010-11-11 03:21:53 +00003653 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003654 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003655
3656 if (OriginalWidth <= FieldWidth)
3657 return false;
3658
Eli Friedman3a643af2012-01-26 23:11:39 +00003659 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003660 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003661 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003662
Eli Friedman3a643af2012-01-26 23:11:39 +00003663 // Check whether the stored value is equal to the original value.
3664 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003665 if (Value == TruncatedValue)
3666 return false;
3667
Eli Friedman3a643af2012-01-26 23:11:39 +00003668 // Special-case bitfields of width 1: booleans are naturally 0/1, and
3669 // therefore don't strictly fit into a bitfield of width 1.
3670 if (FieldWidth == 1 && Value.getBoolValue() == TruncatedValue.getBoolValue())
3671 return false;
3672
John McCall15d7d122010-11-11 03:21:53 +00003673 std::string PrettyValue = Value.toString(10);
3674 std::string PrettyTrunc = TruncatedValue.toString(10);
3675
3676 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3677 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3678 << Init->getSourceRange();
3679
3680 return true;
3681}
3682
John McCallbeb22aa2010-11-09 23:24:47 +00003683/// Analyze the given simple or compound assignment for warning-worthy
3684/// operations.
3685void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3686 // Just recurse on the LHS.
3687 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3688
3689 // We want to recurse on the RHS as normal unless we're assigning to
3690 // a bitfield.
3691 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003692 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3693 E->getOperatorLoc())) {
3694 // Recurse, ignoring any implicit conversions on the RHS.
3695 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3696 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003697 }
3698 }
3699
3700 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3701}
3702
John McCall51313c32010-01-04 23:31:57 +00003703/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003704void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3705 SourceLocation CContext, unsigned diag) {
3706 S.Diag(E->getExprLoc(), diag)
3707 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3708}
3709
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003710/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3711void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3712 unsigned diag) {
3713 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3714}
3715
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003716/// Diagnose an implicit cast from a literal expression. Does not warn when the
3717/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003718void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3719 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003720 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003721 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003722 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003723 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3724 T->hasUnsignedIntegerRepresentation());
3725 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003726 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003727 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003728 return;
3729
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003730 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3731 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003732}
3733
John McCall091f23f2010-11-09 22:22:12 +00003734std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3735 if (!Range.Width) return "0";
3736
3737 llvm::APSInt ValueInRange = Value;
3738 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003739 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003740 return ValueInRange.toString(10);
3741}
3742
John McCall323ed742010-05-06 08:58:33 +00003743void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003744 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003745 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003746
John McCall323ed742010-05-06 08:58:33 +00003747 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3748 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3749 if (Source == Target) return;
3750 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003751
Chandler Carruth108f7562011-07-26 05:40:03 +00003752 // If the conversion context location is invalid don't complain. We also
3753 // don't want to emit a warning if the issue occurs from the expansion of
3754 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3755 // delay this check as long as possible. Once we detect we are in that
3756 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003757 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003758 return;
3759
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003760 // Diagnose implicit casts to bool.
3761 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3762 if (isa<StringLiteral>(E))
3763 // Warn on string literal to bool. Checks for string literals in logical
3764 // expressions, for instances, assert(0 && "error here"), is prevented
3765 // by a check in AnalyzeImplicitConversions().
3766 return DiagnoseImpCast(S, E, T, CC,
3767 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003768 if (Source->isFunctionType()) {
3769 // Warn on function to bool. Checks free functions and static member
3770 // functions. Weakly imported functions are excluded from the check,
3771 // since it's common to test their value to check whether the linker
3772 // found a definition for them.
3773 ValueDecl *D = 0;
3774 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3775 D = R->getDecl();
3776 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3777 D = M->getMemberDecl();
3778 }
3779
3780 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003781 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3782 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3783 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003784 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3785 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3786 QualType ReturnType;
3787 UnresolvedSet<4> NonTemplateOverloads;
3788 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3789 if (!ReturnType.isNull()
3790 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3791 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3792 << FixItHint::CreateInsertion(
3793 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003794 return;
3795 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003796 }
3797 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003798 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003799 }
John McCall51313c32010-01-04 23:31:57 +00003800
3801 // Strip vector types.
3802 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003803 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003804 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003805 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003806 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003807 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003808
3809 // If the vector cast is cast between two vectors of the same size, it is
3810 // a bitcast, not a conversion.
3811 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3812 return;
John McCall51313c32010-01-04 23:31:57 +00003813
3814 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3815 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3816 }
3817
3818 // Strip complex types.
3819 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003820 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003821 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003822 return;
3823
John McCallb4eb64d2010-10-08 02:01:28 +00003824 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003825 }
John McCall51313c32010-01-04 23:31:57 +00003826
3827 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3828 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3829 }
3830
3831 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3832 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3833
3834 // If the source is floating point...
3835 if (SourceBT && SourceBT->isFloatingPoint()) {
3836 // ...and the target is floating point...
3837 if (TargetBT && TargetBT->isFloatingPoint()) {
3838 // ...then warn if we're dropping FP rank.
3839
3840 // Builtin FP kinds are ordered by increasing FP rank.
3841 if (SourceBT->getKind() > TargetBT->getKind()) {
3842 // Don't warn about float constants that are precisely
3843 // representable in the target type.
3844 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003845 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003846 // Value might be a float, a float vector, or a float complex.
3847 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003848 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3849 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003850 return;
3851 }
3852
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003853 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003854 return;
3855
John McCallb4eb64d2010-10-08 02:01:28 +00003856 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003857 }
3858 return;
3859 }
3860
Ted Kremenekef9ff882011-03-10 20:03:42 +00003861 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003862 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003863 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003864 return;
3865
Chandler Carrutha5b93322011-02-17 11:05:49 +00003866 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003867 // We also want to warn on, e.g., "int i = -1.234"
3868 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3869 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3870 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3871
Chandler Carruthf65076e2011-04-10 08:36:24 +00003872 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3873 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003874 } else {
3875 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3876 }
3877 }
John McCall51313c32010-01-04 23:31:57 +00003878
3879 return;
3880 }
3881
John McCallf2370c92010-01-06 05:24:50 +00003882 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003883 return;
3884
Richard Trieu1838ca52011-05-29 19:59:02 +00003885 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3886 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3887 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3888 << E->getSourceRange() << clang::SourceRange(CC);
3889 return;
3890 }
3891
John McCall323ed742010-05-06 08:58:33 +00003892 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003893 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003894
3895 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003896 // If the source is a constant, use a default-on diagnostic.
3897 // TODO: this should happen for bitfield stores, too.
3898 llvm::APSInt Value(32);
3899 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003900 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003901 return;
3902
John McCall091f23f2010-11-09 22:22:12 +00003903 std::string PrettySourceValue = Value.toString(10);
3904 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3905
Ted Kremenek5e745da2011-10-22 02:37:33 +00003906 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3907 S.PDiag(diag::warn_impcast_integer_precision_constant)
3908 << PrettySourceValue << PrettyTargetValue
3909 << E->getType() << T << E->getSourceRange()
3910 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003911 return;
3912 }
3913
Chris Lattnerb792b302011-06-14 04:51:15 +00003914 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003915 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003916 return;
3917
John McCallf2370c92010-01-06 05:24:50 +00003918 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003919 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3920 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003921 }
3922
3923 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3924 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3925 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003926
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003927 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003928 return;
3929
John McCall323ed742010-05-06 08:58:33 +00003930 unsigned DiagID = diag::warn_impcast_integer_sign;
3931
3932 // Traditionally, gcc has warned about this under -Wsign-compare.
3933 // We also want to warn about it in -Wconversion.
3934 // So if -Wconversion is off, use a completely identical diagnostic
3935 // in the sign-compare group.
3936 // The conditional-checking code will
3937 if (ICContext) {
3938 DiagID = diag::warn_impcast_integer_sign_conditional;
3939 *ICContext = true;
3940 }
3941
John McCallb4eb64d2010-10-08 02:01:28 +00003942 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003943 }
3944
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003945 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003946 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3947 // type, to give us better diagnostics.
3948 QualType SourceType = E->getType();
3949 if (!S.getLangOptions().CPlusPlus) {
3950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3951 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3952 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3953 SourceType = S.Context.getTypeDeclType(Enum);
3954 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3955 }
3956 }
3957
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003958 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3959 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3960 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003961 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003962 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003963 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003964 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00003965 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00003966 return;
3967
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003968 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003969 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003970 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003971
John McCall51313c32010-01-04 23:31:57 +00003972 return;
3973}
3974
John McCall323ed742010-05-06 08:58:33 +00003975void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3976
3977void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003978 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003979 E = E->IgnoreParenImpCasts();
3980
3981 if (isa<ConditionalOperator>(E))
3982 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3983
John McCallb4eb64d2010-10-08 02:01:28 +00003984 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003985 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003986 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003987 return;
3988}
3989
3990void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003991 SourceLocation CC = E->getQuestionLoc();
3992
3993 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003994
3995 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003996 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3997 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003998
3999 // If -Wconversion would have warned about either of the candidates
4000 // for a signedness conversion to the context type...
4001 if (!Suspicious) return;
4002
4003 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004004 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4005 CC))
John McCall323ed742010-05-06 08:58:33 +00004006 return;
4007
John McCall323ed742010-05-06 08:58:33 +00004008 // ...then check whether it would have warned about either of the
4009 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004010 if (E->getType() == T) return;
4011
4012 Suspicious = false;
4013 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4014 E->getType(), CC, &Suspicious);
4015 if (!Suspicious)
4016 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004017 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004018}
4019
4020/// AnalyzeImplicitConversions - Find and report any interesting
4021/// implicit conversions in the given expression. There are a couple
4022/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004023void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004024 QualType T = OrigE->getType();
4025 Expr *E = OrigE->IgnoreParenImpCasts();
4026
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004027 if (E->isTypeDependent() || E->isValueDependent())
4028 return;
4029
John McCall323ed742010-05-06 08:58:33 +00004030 // For conditional operators, we analyze the arguments as if they
4031 // were being fed directly into the output.
4032 if (isa<ConditionalOperator>(E)) {
4033 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4034 CheckConditionalOperator(S, CO, T);
4035 return;
4036 }
4037
4038 // Go ahead and check any implicit conversions we might have skipped.
4039 // The non-canonical typecheck is just an optimization;
4040 // CheckImplicitConversion will filter out dead implicit conversions.
4041 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004042 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004043
4044 // Now continue drilling into this expression.
4045
4046 // Skip past explicit casts.
4047 if (isa<ExplicitCastExpr>(E)) {
4048 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004049 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004050 }
4051
John McCallbeb22aa2010-11-09 23:24:47 +00004052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4053 // Do a somewhat different check with comparison operators.
4054 if (BO->isComparisonOp())
4055 return AnalyzeComparison(S, BO);
4056
Eli Friedman0fa06382012-01-26 23:34:06 +00004057 // And with simple assignments.
4058 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004059 return AnalyzeAssignment(S, BO);
4060 }
John McCall323ed742010-05-06 08:58:33 +00004061
4062 // These break the otherwise-useful invariant below. Fortunately,
4063 // we don't really need to recurse into them, because any internal
4064 // expressions should have been analyzed already when they were
4065 // built into statements.
4066 if (isa<StmtExpr>(E)) return;
4067
4068 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004069 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004070
4071 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004072 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004073 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4074 bool IsLogicalOperator = BO && BO->isLogicalOp();
4075 for (Stmt::child_range I = E->children(); I; ++I) {
4076 Expr *ChildExpr = cast<Expr>(*I);
4077 if (IsLogicalOperator &&
4078 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4079 // Ignore checking string literals that are in logical operators.
4080 continue;
4081 AnalyzeImplicitConversions(S, ChildExpr, CC);
4082 }
John McCall323ed742010-05-06 08:58:33 +00004083}
4084
4085} // end anonymous namespace
4086
4087/// Diagnoses "dangerous" implicit conversions within the given
4088/// expression (which is a full expression). Implements -Wconversion
4089/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004090///
4091/// \param CC the "context" location of the implicit conversion, i.e.
4092/// the most location of the syntactic entity requiring the implicit
4093/// conversion
4094void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004095 // Don't diagnose in unevaluated contexts.
4096 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4097 return;
4098
4099 // Don't diagnose for value- or type-dependent expressions.
4100 if (E->isTypeDependent() || E->isValueDependent())
4101 return;
4102
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004103 // Check for array bounds violations in cases where the check isn't triggered
4104 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4105 // ArraySubscriptExpr is on the RHS of a variable initialization.
4106 CheckArrayAccess(E);
4107
John McCallb4eb64d2010-10-08 02:01:28 +00004108 // This is not the right CC for (e.g.) a variable initialization.
4109 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004110}
4111
John McCall15d7d122010-11-11 03:21:53 +00004112void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4113 FieldDecl *BitField,
4114 Expr *Init) {
4115 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4116}
4117
Mike Stumpf8c49212010-01-21 03:59:47 +00004118/// CheckParmsForFunctionDef - Check that the parameters of the given
4119/// function are appropriate for the definition of a function. This
4120/// takes care of any checks that cannot be performed on the
4121/// declaration itself, e.g., that the types of each of the function
4122/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004123bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4124 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004125 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004126 for (; P != PEnd; ++P) {
4127 ParmVarDecl *Param = *P;
4128
Mike Stumpf8c49212010-01-21 03:59:47 +00004129 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4130 // function declarator that is part of a function definition of
4131 // that function shall not have incomplete type.
4132 //
4133 // This is also C++ [dcl.fct]p6.
4134 if (!Param->isInvalidDecl() &&
4135 RequireCompleteType(Param->getLocation(), Param->getType(),
4136 diag::err_typecheck_decl_incomplete_type)) {
4137 Param->setInvalidDecl();
4138 HasInvalidParm = true;
4139 }
4140
4141 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4142 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004143 if (CheckParameterNames &&
4144 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004145 !Param->isImplicit() &&
4146 !getLangOptions().CPlusPlus)
4147 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004148
4149 // C99 6.7.5.3p12:
4150 // If the function declarator is not part of a definition of that
4151 // function, parameters may have incomplete type and may use the [*]
4152 // notation in their sequences of declarator specifiers to specify
4153 // variable length array types.
4154 QualType PType = Param->getOriginalType();
4155 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4156 if (AT->getSizeModifier() == ArrayType::Star) {
4157 // FIXME: This diagnosic should point the the '[*]' if source-location
4158 // information is added for it.
4159 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4160 }
4161 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004162 }
4163
4164 return HasInvalidParm;
4165}
John McCallb7f4ffe2010-08-12 21:44:57 +00004166
4167/// CheckCastAlign - Implements -Wcast-align, which warns when a
4168/// pointer cast increases the alignment requirements.
4169void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4170 // This is actually a lot of work to potentially be doing on every
4171 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004172 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4173 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004174 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004175 return;
4176
4177 // Ignore dependent types.
4178 if (T->isDependentType() || Op->getType()->isDependentType())
4179 return;
4180
4181 // Require that the destination be a pointer type.
4182 const PointerType *DestPtr = T->getAs<PointerType>();
4183 if (!DestPtr) return;
4184
4185 // If the destination has alignment 1, we're done.
4186 QualType DestPointee = DestPtr->getPointeeType();
4187 if (DestPointee->isIncompleteType()) return;
4188 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4189 if (DestAlign.isOne()) return;
4190
4191 // Require that the source be a pointer type.
4192 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4193 if (!SrcPtr) return;
4194 QualType SrcPointee = SrcPtr->getPointeeType();
4195
4196 // Whitelist casts from cv void*. We already implicitly
4197 // whitelisted casts to cv void*, since they have alignment 1.
4198 // Also whitelist casts involving incomplete types, which implicitly
4199 // includes 'void'.
4200 if (SrcPointee->isIncompleteType()) return;
4201
4202 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4203 if (SrcAlign >= DestAlign) return;
4204
4205 Diag(TRange.getBegin(), diag::warn_cast_align)
4206 << Op->getType() << T
4207 << static_cast<unsigned>(SrcAlign.getQuantity())
4208 << static_cast<unsigned>(DestAlign.getQuantity())
4209 << TRange << Op->getSourceRange();
4210}
4211
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004212static const Type* getElementType(const Expr *BaseExpr) {
4213 const Type* EltType = BaseExpr->getType().getTypePtr();
4214 if (EltType->isAnyPointerType())
4215 return EltType->getPointeeType().getTypePtr();
4216 else if (EltType->isArrayType())
4217 return EltType->getBaseElementTypeUnsafe();
4218 return EltType;
4219}
4220
Chandler Carruthc2684342011-08-05 09:10:50 +00004221/// \brief Check whether this array fits the idiom of a size-one tail padded
4222/// array member of a struct.
4223///
4224/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4225/// commonly used to emulate flexible arrays in C89 code.
4226static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4227 const NamedDecl *ND) {
4228 if (Size != 1 || !ND) return false;
4229
4230 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4231 if (!FD) return false;
4232
4233 // Don't consider sizes resulting from macro expansions or template argument
4234 // substitution to form C89 tail-padded arrays.
4235 ConstantArrayTypeLoc TL =
4236 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4237 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4238 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4239 return false;
4240
4241 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004242 if (!RD) return false;
4243 if (RD->isUnion()) return false;
4244 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4245 if (!CRD->isStandardLayout()) return false;
4246 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004247
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004248 // See if this is the last field decl in the record.
4249 const Decl *D = FD;
4250 while ((D = D->getNextDeclInContext()))
4251 if (isa<FieldDecl>(D))
4252 return false;
4253 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004254}
4255
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004256void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004257 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004258 bool AllowOnePastEnd, bool IndexNegated) {
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004259 IndexExpr = IndexExpr->IgnoreParenCasts();
4260 if (IndexExpr->isValueDependent())
4261 return;
4262
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004263 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004264 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004265 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004266 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004267 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004268 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004269
Chandler Carruth34064582011-02-17 20:55:08 +00004270 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004271 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004272 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004273 if (IndexNegated)
4274 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004275
Chandler Carruthba447122011-08-05 08:07:29 +00004276 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4278 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004279 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004280 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004281
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004282 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004283 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004284 if (!size.isStrictlyPositive())
4285 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004286
4287 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004288 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004289 // Make sure we're comparing apples to apples when comparing index to size
4290 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4291 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004292 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004293 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004294 if (ptrarith_typesize != array_typesize) {
4295 // There's a cast to a different size type involved
4296 uint64_t ratio = array_typesize / ptrarith_typesize;
4297 // TODO: Be smarter about handling cases where array_typesize is not a
4298 // multiple of ptrarith_typesize
4299 if (ptrarith_typesize * ratio == array_typesize)
4300 size *= llvm::APInt(size.getBitWidth(), ratio);
4301 }
4302 }
4303
Chandler Carruth34064582011-02-17 20:55:08 +00004304 if (size.getBitWidth() > index.getBitWidth())
4305 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004306 else if (size.getBitWidth() < index.getBitWidth())
4307 size = size.sext(index.getBitWidth());
4308
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004309 // For array subscripting the index must be less than size, but for pointer
4310 // arithmetic also allow the index (offset) to be equal to size since
4311 // computing the next address after the end of the array is legal and
4312 // commonly done e.g. in C++ iterators and range-based for loops.
4313 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004314 return;
4315
4316 // Also don't warn for arrays of size 1 which are members of some
4317 // structure. These are often used to approximate flexible arrays in C89
4318 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004319 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004320 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004321
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004322 // Suppress the warning if the subscript expression (as identified by the
4323 // ']' location) and the index expression are both from macro expansions
4324 // within a system header.
4325 if (ASE) {
4326 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4327 ASE->getRBracketLoc());
4328 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4329 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4330 IndexExpr->getLocStart());
4331 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4332 return;
4333 }
4334 }
4335
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004336 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004337 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004338 DiagID = diag::warn_array_index_exceeds_bounds;
4339
4340 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4341 PDiag(DiagID) << index.toString(10, true)
4342 << size.toString(10, true)
4343 << (unsigned)size.getLimitedValue(~0U)
4344 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004345 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004346 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004347 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004348 DiagID = diag::warn_ptr_arith_precedes_bounds;
4349 if (index.isNegative()) index = -index;
4350 }
4351
4352 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4353 PDiag(DiagID) << index.toString(10, true)
4354 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004355 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004356
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004357 if (!ND) {
4358 // Try harder to find a NamedDecl to point at in the note.
4359 while (const ArraySubscriptExpr *ASE =
4360 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4361 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4362 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4363 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4364 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4365 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4366 }
4367
Chandler Carruth35001ca2011-02-17 21:10:52 +00004368 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004369 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4370 PDiag(diag::note_array_index_out_of_bounds)
4371 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004372}
4373
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004374void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004375 int AllowOnePastEnd = 0;
4376 while (expr) {
4377 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004378 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004379 case Stmt::ArraySubscriptExprClass: {
4380 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004381 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004382 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004383 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004384 }
4385 case Stmt::UnaryOperatorClass: {
4386 // Only unwrap the * and & unary operators
4387 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4388 expr = UO->getSubExpr();
4389 switch (UO->getOpcode()) {
4390 case UO_AddrOf:
4391 AllowOnePastEnd++;
4392 break;
4393 case UO_Deref:
4394 AllowOnePastEnd--;
4395 break;
4396 default:
4397 return;
4398 }
4399 break;
4400 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004401 case Stmt::ConditionalOperatorClass: {
4402 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4403 if (const Expr *lhs = cond->getLHS())
4404 CheckArrayAccess(lhs);
4405 if (const Expr *rhs = cond->getRHS())
4406 CheckArrayAccess(rhs);
4407 return;
4408 }
4409 default:
4410 return;
4411 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004412 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004413}
John McCallf85e1932011-06-15 23:02:42 +00004414
4415//===--- CHECK: Objective-C retain cycles ----------------------------------//
4416
4417namespace {
4418 struct RetainCycleOwner {
4419 RetainCycleOwner() : Variable(0), Indirect(false) {}
4420 VarDecl *Variable;
4421 SourceRange Range;
4422 SourceLocation Loc;
4423 bool Indirect;
4424
4425 void setLocsFrom(Expr *e) {
4426 Loc = e->getExprLoc();
4427 Range = e->getSourceRange();
4428 }
4429 };
4430}
4431
4432/// Consider whether capturing the given variable can possibly lead to
4433/// a retain cycle.
4434static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4435 // In ARC, it's captured strongly iff the variable has __strong
4436 // lifetime. In MRR, it's captured strongly if the variable is
4437 // __block and has an appropriate type.
4438 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4439 return false;
4440
4441 owner.Variable = var;
4442 owner.setLocsFrom(ref);
4443 return true;
4444}
4445
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004446static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004447 while (true) {
4448 e = e->IgnoreParens();
4449 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4450 switch (cast->getCastKind()) {
4451 case CK_BitCast:
4452 case CK_LValueBitCast:
4453 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004454 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004455 e = cast->getSubExpr();
4456 continue;
4457
John McCallf85e1932011-06-15 23:02:42 +00004458 default:
4459 return false;
4460 }
4461 }
4462
4463 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4464 ObjCIvarDecl *ivar = ref->getDecl();
4465 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4466 return false;
4467
4468 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004469 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004470 return false;
4471
4472 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4473 owner.Indirect = true;
4474 return true;
4475 }
4476
4477 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4478 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4479 if (!var) return false;
4480 return considerVariable(var, ref, owner);
4481 }
4482
4483 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4484 owner.Variable = ref->getDecl();
4485 owner.setLocsFrom(ref);
4486 return true;
4487 }
4488
4489 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4490 if (member->isArrow()) return false;
4491
4492 // Don't count this as an indirect ownership.
4493 e = member->getBase();
4494 continue;
4495 }
4496
John McCall4b9c2d22011-11-06 09:01:30 +00004497 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4498 // Only pay attention to pseudo-objects on property references.
4499 ObjCPropertyRefExpr *pre
4500 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4501 ->IgnoreParens());
4502 if (!pre) return false;
4503 if (pre->isImplicitProperty()) return false;
4504 ObjCPropertyDecl *property = pre->getExplicitProperty();
4505 if (!property->isRetaining() &&
4506 !(property->getPropertyIvarDecl() &&
4507 property->getPropertyIvarDecl()->getType()
4508 .getObjCLifetime() == Qualifiers::OCL_Strong))
4509 return false;
4510
4511 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004512 if (pre->isSuperReceiver()) {
4513 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4514 if (!owner.Variable)
4515 return false;
4516 owner.Loc = pre->getLocation();
4517 owner.Range = pre->getSourceRange();
4518 return true;
4519 }
John McCall4b9c2d22011-11-06 09:01:30 +00004520 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4521 ->getSourceExpr());
4522 continue;
4523 }
4524
John McCallf85e1932011-06-15 23:02:42 +00004525 // Array ivars?
4526
4527 return false;
4528 }
4529}
4530
4531namespace {
4532 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4533 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4534 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4535 Variable(variable), Capturer(0) {}
4536
4537 VarDecl *Variable;
4538 Expr *Capturer;
4539
4540 void VisitDeclRefExpr(DeclRefExpr *ref) {
4541 if (ref->getDecl() == Variable && !Capturer)
4542 Capturer = ref;
4543 }
4544
4545 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4546 if (ref->getDecl() == Variable && !Capturer)
4547 Capturer = ref;
4548 }
4549
4550 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4551 if (Capturer) return;
4552 Visit(ref->getBase());
4553 if (Capturer && ref->isFreeIvar())
4554 Capturer = ref;
4555 }
4556
4557 void VisitBlockExpr(BlockExpr *block) {
4558 // Look inside nested blocks
4559 if (block->getBlockDecl()->capturesVariable(Variable))
4560 Visit(block->getBlockDecl()->getBody());
4561 }
4562 };
4563}
4564
4565/// Check whether the given argument is a block which captures a
4566/// variable.
4567static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4568 assert(owner.Variable && owner.Loc.isValid());
4569
4570 e = e->IgnoreParenCasts();
4571 BlockExpr *block = dyn_cast<BlockExpr>(e);
4572 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4573 return 0;
4574
4575 FindCaptureVisitor visitor(S.Context, owner.Variable);
4576 visitor.Visit(block->getBlockDecl()->getBody());
4577 return visitor.Capturer;
4578}
4579
4580static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4581 RetainCycleOwner &owner) {
4582 assert(capturer);
4583 assert(owner.Variable && owner.Loc.isValid());
4584
4585 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4586 << owner.Variable << capturer->getSourceRange();
4587 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4588 << owner.Indirect << owner.Range;
4589}
4590
4591/// Check for a keyword selector that starts with the word 'add' or
4592/// 'set'.
4593static bool isSetterLikeSelector(Selector sel) {
4594 if (sel.isUnarySelector()) return false;
4595
Chris Lattner5f9e2722011-07-23 10:55:15 +00004596 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004597 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004598 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004599 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004600 else if (str.startswith("add")) {
4601 // Specially whitelist 'addOperationWithBlock:'.
4602 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4603 return false;
4604 str = str.substr(3);
4605 }
John McCallf85e1932011-06-15 23:02:42 +00004606 else
4607 return false;
4608
4609 if (str.empty()) return true;
4610 return !islower(str.front());
4611}
4612
4613/// Check a message send to see if it's likely to cause a retain cycle.
4614void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4615 // Only check instance methods whose selector looks like a setter.
4616 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4617 return;
4618
4619 // Try to find a variable that the receiver is strongly owned by.
4620 RetainCycleOwner owner;
4621 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004622 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004623 return;
4624 } else {
4625 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4626 owner.Variable = getCurMethodDecl()->getSelfDecl();
4627 owner.Loc = msg->getSuperLoc();
4628 owner.Range = msg->getSuperLoc();
4629 }
4630
4631 // Check whether the receiver is captured by any of the arguments.
4632 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4633 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4634 return diagnoseRetainCycle(*this, capturer, owner);
4635}
4636
4637/// Check a property assign to see if it's likely to cause a retain cycle.
4638void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4639 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004640 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004641 return;
4642
4643 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4644 diagnoseRetainCycle(*this, capturer, owner);
4645}
4646
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004647bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004648 QualType LHS, Expr *RHS) {
4649 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4650 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004651 return false;
4652 // strip off any implicit cast added to get to the one arc-specific
4653 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004654 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004655 Diag(Loc, diag::warn_arc_retained_assign)
4656 << (LT == Qualifiers::OCL_ExplicitNone)
4657 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004658 return true;
4659 }
4660 RHS = cast->getSubExpr();
4661 }
4662 return false;
John McCallf85e1932011-06-15 23:02:42 +00004663}
4664
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004665void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4666 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004667 QualType LHSType;
4668 // PropertyRef on LHS type need be directly obtained from
4669 // its declaration as it has a PsuedoType.
4670 ObjCPropertyRefExpr *PRE
4671 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4672 if (PRE && !PRE->isImplicitProperty()) {
4673 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4674 if (PD)
4675 LHSType = PD->getType();
4676 }
4677
4678 if (LHSType.isNull())
4679 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004680 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4681 return;
4682 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4683 // FIXME. Check for other life times.
4684 if (LT != Qualifiers::OCL_None)
4685 return;
4686
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004687 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004688 if (PRE->isImplicitProperty())
4689 return;
4690 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4691 if (!PD)
4692 return;
4693
4694 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004695 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4696 // when 'assign' attribute was not explicitly specified
4697 // by user, ignore it and rely on property type itself
4698 // for lifetime info.
4699 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4700 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4701 LHSType->isObjCRetainableType())
4702 return;
4703
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004704 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004705 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004706 Diag(Loc, diag::warn_arc_retained_property_assign)
4707 << RHS->getSourceRange();
4708 return;
4709 }
4710 RHS = cast->getSubExpr();
4711 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004712 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004713 }
4714}