blob: 1fc3c1aeff30d86105d8f75be077037f6704c970 [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"
David Blaikiebe0ee872012-05-15 16:56:36 +000025#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000026#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000027#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "clang/AST/DeclObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000032#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000033#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000035#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000036#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000037#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000038#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000039#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
John McCall60d7b3a2010-08-24 06:29:42 +000098ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000099Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000100 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000101
Chris Lattner946928f2010-10-01 23:23:24 +0000102 // Find out if any arguments are required to be integer constant expressions.
103 unsigned ICEArguments = 0;
104 ASTContext::GetBuiltinTypeError Error;
105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106 if (Error != ASTContext::GE_None)
107 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
108
109 // If any arguments are required to be ICE's, check and diagnose.
110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111 // Skip arguments not required to be ICE's.
112 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114 llvm::APSInt Result;
115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116 return true;
117 ICEArguments &= ~(1 << ArgNo);
118 }
119
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000122 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000124 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000127 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinVAStart(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 case Builtin::BI__builtin_isgreater:
133 case Builtin::BI__builtin_isgreaterequal:
134 case Builtin::BI__builtin_isless:
135 case Builtin::BI__builtin_islessequal:
136 case Builtin::BI__builtin_islessgreater:
137 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinUnorderedCompare(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000141 case Builtin::BI__builtin_fpclassify:
142 if (SemaBuiltinFPClassification(TheCall, 6))
143 return ExprError();
144 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000145 case Builtin::BI__builtin_isfinite:
146 case Builtin::BI__builtin_isinf:
147 case Builtin::BI__builtin_isinf_sign:
148 case Builtin::BI__builtin_isnan:
149 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000150 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 return ExprError();
152 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000153 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 return SemaBuiltinShuffleVector(TheCall);
155 // TheCall will be freed by the smart pointer here, but that's fine, since
156 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000157 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinPrefetch(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000161 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 if (SemaBuiltinObjectSize(TheCall))
163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000165 case Builtin::BI__builtin_longjmp:
166 if (SemaBuiltinLongjmp(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000169
170 case Builtin::BI__builtin_classify_type:
171 if (checkArgCount(*this, TheCall, 1)) return true;
172 TheCall->setType(Context.IntTy);
173 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000174 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000175 if (checkArgCount(*this, TheCall, 1)) return true;
176 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000177 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000178 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000179 case Builtin::BI__sync_fetch_and_add_1:
180 case Builtin::BI__sync_fetch_and_add_2:
181 case Builtin::BI__sync_fetch_and_add_4:
182 case Builtin::BI__sync_fetch_and_add_8:
183 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000184 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000185 case Builtin::BI__sync_fetch_and_sub_1:
186 case Builtin::BI__sync_fetch_and_sub_2:
187 case Builtin::BI__sync_fetch_and_sub_4:
188 case Builtin::BI__sync_fetch_and_sub_8:
189 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000190 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000191 case Builtin::BI__sync_fetch_and_or_1:
192 case Builtin::BI__sync_fetch_and_or_2:
193 case Builtin::BI__sync_fetch_and_or_4:
194 case Builtin::BI__sync_fetch_and_or_8:
195 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000196 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000197 case Builtin::BI__sync_fetch_and_and_1:
198 case Builtin::BI__sync_fetch_and_and_2:
199 case Builtin::BI__sync_fetch_and_and_4:
200 case Builtin::BI__sync_fetch_and_and_8:
201 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000202 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000203 case Builtin::BI__sync_fetch_and_xor_1:
204 case Builtin::BI__sync_fetch_and_xor_2:
205 case Builtin::BI__sync_fetch_and_xor_4:
206 case Builtin::BI__sync_fetch_and_xor_8:
207 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000208 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000209 case Builtin::BI__sync_add_and_fetch_1:
210 case Builtin::BI__sync_add_and_fetch_2:
211 case Builtin::BI__sync_add_and_fetch_4:
212 case Builtin::BI__sync_add_and_fetch_8:
213 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000215 case Builtin::BI__sync_sub_and_fetch_1:
216 case Builtin::BI__sync_sub_and_fetch_2:
217 case Builtin::BI__sync_sub_and_fetch_4:
218 case Builtin::BI__sync_sub_and_fetch_8:
219 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000220 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000221 case Builtin::BI__sync_and_and_fetch_1:
222 case Builtin::BI__sync_and_and_fetch_2:
223 case Builtin::BI__sync_and_and_fetch_4:
224 case Builtin::BI__sync_and_and_fetch_8:
225 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000226 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000227 case Builtin::BI__sync_or_and_fetch_1:
228 case Builtin::BI__sync_or_and_fetch_2:
229 case Builtin::BI__sync_or_and_fetch_4:
230 case Builtin::BI__sync_or_and_fetch_8:
231 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000232 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000233 case Builtin::BI__sync_xor_and_fetch_1:
234 case Builtin::BI__sync_xor_and_fetch_2:
235 case Builtin::BI__sync_xor_and_fetch_4:
236 case Builtin::BI__sync_xor_and_fetch_8:
237 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000238 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000239 case Builtin::BI__sync_val_compare_and_swap_1:
240 case Builtin::BI__sync_val_compare_and_swap_2:
241 case Builtin::BI__sync_val_compare_and_swap_4:
242 case Builtin::BI__sync_val_compare_and_swap_8:
243 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000244 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000245 case Builtin::BI__sync_bool_compare_and_swap_1:
246 case Builtin::BI__sync_bool_compare_and_swap_2:
247 case Builtin::BI__sync_bool_compare_and_swap_4:
248 case Builtin::BI__sync_bool_compare_and_swap_8:
249 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000250 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000251 case Builtin::BI__sync_lock_test_and_set_1:
252 case Builtin::BI__sync_lock_test_and_set_2:
253 case Builtin::BI__sync_lock_test_and_set_4:
254 case Builtin::BI__sync_lock_test_and_set_8:
255 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000256 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000257 case Builtin::BI__sync_lock_release_1:
258 case Builtin::BI__sync_lock_release_2:
259 case Builtin::BI__sync_lock_release_4:
260 case Builtin::BI__sync_lock_release_8:
261 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000262 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000263 case Builtin::BI__sync_swap_1:
264 case Builtin::BI__sync_swap_2:
265 case Builtin::BI__sync_swap_4:
266 case Builtin::BI__sync_swap_8:
267 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000268 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Richard Smithff34d402012-04-12 05:08:17 +0000269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271 case Builtin::BI##ID: \
272 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID);
273#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000274 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000275 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 return ExprError();
277 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000278 }
279
280 // Since the target specific builtins for each arch overlap, only check those
281 // of the arch we are compiling for.
282 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000283 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000284 case llvm::Triple::arm:
285 case llvm::Triple::thumb:
286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287 return ExprError();
288 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000289 default:
290 break;
291 }
292 }
293
294 return move(TheCallResult);
295}
296
Nate Begeman61eecf52010-06-14 05:21:25 +0000297// Get the valid immediate range for the specified NEON type code.
298static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000299 NeonTypeFlags Type(t);
300 int IsQuad = Type.isQuad();
301 switch (Type.getEltType()) {
302 case NeonTypeFlags::Int8:
303 case NeonTypeFlags::Poly8:
304 return shift ? 7 : (8 << IsQuad) - 1;
305 case NeonTypeFlags::Int16:
306 case NeonTypeFlags::Poly16:
307 return shift ? 15 : (4 << IsQuad) - 1;
308 case NeonTypeFlags::Int32:
309 return shift ? 31 : (2 << IsQuad) - 1;
310 case NeonTypeFlags::Int64:
311 return shift ? 63 : (1 << IsQuad) - 1;
312 case NeonTypeFlags::Float16:
313 assert(!shift && "cannot shift float types!");
314 return (4 << IsQuad) - 1;
315 case NeonTypeFlags::Float32:
316 assert(!shift && "cannot shift float types!");
317 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000318 }
David Blaikie7530c032012-01-17 06:56:22 +0000319 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000320}
321
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000322/// getNeonEltType - Return the QualType corresponding to the elements of
323/// the vector type specified by the NeonTypeFlags. This is used to check
324/// the pointer arguments for Neon load/store intrinsics.
325static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
326 switch (Flags.getEltType()) {
327 case NeonTypeFlags::Int8:
328 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
329 case NeonTypeFlags::Int16:
330 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
331 case NeonTypeFlags::Int32:
332 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
333 case NeonTypeFlags::Int64:
334 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
335 case NeonTypeFlags::Poly8:
336 return Context.SignedCharTy;
337 case NeonTypeFlags::Poly16:
338 return Context.ShortTy;
339 case NeonTypeFlags::Float16:
340 return Context.UnsignedShortTy;
341 case NeonTypeFlags::Float32:
342 return Context.FloatTy;
343 }
David Blaikie7530c032012-01-17 06:56:22 +0000344 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000345}
346
Nate Begeman26a31422010-06-08 02:47:44 +0000347bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000348 llvm::APSInt Result;
349
Nate Begeman0d15c532010-06-13 04:47:52 +0000350 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000351 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000352 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000354 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000355#define GET_NEON_OVERLOAD_CHECK
356#include "clang/Basic/arm_neon.inc"
357#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000358 }
359
Nate Begeman0d15c532010-06-13 04:47:52 +0000360 // For NEON intrinsics which are overloaded on vector element type, validate
361 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000362 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000363 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000364 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000365 return true;
366
Bob Wilsonda95f732011-11-08 01:16:11 +0000367 TV = Result.getLimitedValue(64);
368 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000369 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 << TheCall->getArg(ImmArg)->getSourceRange();
371 }
372
Bob Wilson46482552011-11-16 21:32:23 +0000373 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000374 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000375 Expr *Arg = TheCall->getArg(PtrArgNum);
376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
377 Arg = ICE->getSubExpr();
378 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
379 QualType RHSTy = RHS.get()->getType();
380 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
381 if (HasConstPtr)
382 EltTy = EltTy.withConst();
383 QualType LHSTy = Context.getPointerType(EltTy);
384 AssignConvertType ConvTy;
385 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
386 if (RHS.isInvalid())
387 return true;
388 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
389 RHS.get(), AA_Assigning))
390 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000391 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000392
Nate Begeman0d15c532010-06-13 04:47:52 +0000393 // For NEON intrinsics which take an immediate value as part of the
394 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000395 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 switch (BuiltinID) {
397 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000400 case ARM::BI__builtin_arm_vcvtr_f:
401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000402#define GET_NEON_IMMEDIATE_CHECK
403#include "clang/Basic/arm_neon.inc"
404#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000405 };
406
Nate Begeman61eecf52010-06-14 05:21:25 +0000407 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000408 if (SemaBuiltinConstantArg(TheCall, i, Result))
409 return true;
410
Nate Begeman61eecf52010-06-14 05:21:25 +0000411 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000412 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000413 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000414 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000415 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000416
Nate Begeman99c40bb2010-08-03 21:32:34 +0000417 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000418 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000419}
Daniel Dunbarde454282008-10-02 18:44:07 +0000420
Anders Carlssond406bf02009-08-16 01:56:34 +0000421/// CheckFunctionCall - Check a direct function call for various correctness
422/// and safety properties not strictly enforced by the C type system.
423bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
424 // Get the IdentifierInfo* for the called function.
425 IdentifierInfo *FnInfo = FDecl->getIdentifier();
426
427 // None of the checks below are needed for functions that don't have
428 // simple names (e.g., C++ conversion functions).
429 if (!FnInfo)
430 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Daniel Dunbarde454282008-10-02 18:44:07 +0000432 // FIXME: This mechanism should be abstracted to be less fragile and
433 // more efficient. For example, just map function ids to custom
434 // handlers.
435
Ted Kremenekc82faca2010-09-09 04:33:05 +0000436 // Printf and scanf checking.
437 for (specific_attr_iterator<FormatAttr>
438 i = FDecl->specific_attr_begin<FormatAttr>(),
439 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000440 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Ted Kremenekc82faca2010-09-09 04:33:05 +0000443 for (specific_attr_iterator<NonNullAttr>
444 i = FDecl->specific_attr_begin<NonNullAttr>(),
445 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000446 CheckNonNullArguments(*i, TheCall->getArgs(),
447 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000448 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000449
Anna Zaks0a151a12012-01-17 00:37:07 +0000450 unsigned CMId = FDecl->getMemoryFunctionKind();
451 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000452 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000453
Anna Zaksd9b859a2012-01-13 21:52:01 +0000454 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000455 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000456 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000457 else if (CMId == Builtin::BIstrncat)
458 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000459 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000460 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000461
Anders Carlssond406bf02009-08-16 01:56:34 +0000462 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000463}
464
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000465bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
466 Expr **Args, unsigned NumArgs) {
467 for (specific_attr_iterator<FormatAttr>
468 i = Method->specific_attr_begin<FormatAttr>(),
469 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
470
471 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
472 Method->getSourceRange());
473 }
474
475 // diagnose nonnull arguments.
476 for (specific_attr_iterator<NonNullAttr>
477 i = Method->specific_attr_begin<NonNullAttr>(),
478 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
479 CheckNonNullArguments(*i, Args, lbrac);
480 }
481
482 return false;
483}
484
Anders Carlssond406bf02009-08-16 01:56:34 +0000485bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000486 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
487 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000488 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000490 QualType Ty = V->getType();
491 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000492 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000494 // format string checking.
495 for (specific_attr_iterator<FormatAttr>
496 i = NDecl->specific_attr_begin<FormatAttr>(),
497 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
498 CheckFormatArguments(*i, TheCall);
499 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000500
501 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000502}
503
Richard Smithff34d402012-04-12 05:08:17 +0000504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
505 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000508
Richard Smithff34d402012-04-12 05:08:17 +0000509 // All these operations take one of the following forms:
510 enum {
511 // C __c11_atomic_init(A *, C)
512 Init,
513 // C __c11_atomic_load(A *, int)
514 Load,
515 // void __atomic_load(A *, CP, int)
516 Copy,
517 // C __c11_atomic_add(A *, M, int)
518 Arithmetic,
519 // C __atomic_exchange_n(A *, CP, int)
520 Xchg,
521 // void __atomic_exchange(A *, C *, CP, int)
522 GNUXchg,
523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
524 C11CmpXchg,
525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
526 GNUCmpXchg
527 } Form = Init;
528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
530 // where:
531 // C is an appropriate type,
532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
535 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000536
Richard Smithff34d402012-04-12 05:08:17 +0000537 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
539 && "need to update code for modified C11 atomics");
540 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
541 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
542 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
543 Op == AtomicExpr::AO__atomic_store_n ||
544 Op == AtomicExpr::AO__atomic_exchange_n ||
545 Op == AtomicExpr::AO__atomic_compare_exchange_n;
546 bool IsAddSub = false;
547
548 switch (Op) {
549 case AtomicExpr::AO__c11_atomic_init:
550 Form = Init;
551 break;
552
553 case AtomicExpr::AO__c11_atomic_load:
554 case AtomicExpr::AO__atomic_load_n:
555 Form = Load;
556 break;
557
558 case AtomicExpr::AO__c11_atomic_store:
559 case AtomicExpr::AO__atomic_load:
560 case AtomicExpr::AO__atomic_store:
561 case AtomicExpr::AO__atomic_store_n:
562 Form = Copy;
563 break;
564
565 case AtomicExpr::AO__c11_atomic_fetch_add:
566 case AtomicExpr::AO__c11_atomic_fetch_sub:
567 case AtomicExpr::AO__atomic_fetch_add:
568 case AtomicExpr::AO__atomic_fetch_sub:
569 case AtomicExpr::AO__atomic_add_fetch:
570 case AtomicExpr::AO__atomic_sub_fetch:
571 IsAddSub = true;
572 // Fall through.
573 case AtomicExpr::AO__c11_atomic_fetch_and:
574 case AtomicExpr::AO__c11_atomic_fetch_or:
575 case AtomicExpr::AO__c11_atomic_fetch_xor:
576 case AtomicExpr::AO__atomic_fetch_and:
577 case AtomicExpr::AO__atomic_fetch_or:
578 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000579 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000580 case AtomicExpr::AO__atomic_and_fetch:
581 case AtomicExpr::AO__atomic_or_fetch:
582 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000583 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000584 Form = Arithmetic;
585 break;
586
587 case AtomicExpr::AO__c11_atomic_exchange:
588 case AtomicExpr::AO__atomic_exchange_n:
589 Form = Xchg;
590 break;
591
592 case AtomicExpr::AO__atomic_exchange:
593 Form = GNUXchg;
594 break;
595
596 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
597 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
598 Form = C11CmpXchg;
599 break;
600
601 case AtomicExpr::AO__atomic_compare_exchange:
602 case AtomicExpr::AO__atomic_compare_exchange_n:
603 Form = GNUCmpXchg;
604 break;
605 }
606
607 // Check we have the right number of arguments.
608 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000609 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000610 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000611 << TheCall->getCallee()->getSourceRange();
612 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000613 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
614 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000615 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000616 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000617 << TheCall->getCallee()->getSourceRange();
618 return ExprError();
619 }
620
Richard Smithff34d402012-04-12 05:08:17 +0000621 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000622 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000623 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
624 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
625 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000626 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000627 << Ptr->getType() << Ptr->getSourceRange();
628 return ExprError();
629 }
630
Richard Smithff34d402012-04-12 05:08:17 +0000631 // For a __c11 builtin, this should be a pointer to an _Atomic type.
632 QualType AtomTy = pointerType->getPointeeType(); // 'A'
633 QualType ValType = AtomTy; // 'C'
634 if (IsC11) {
635 if (!AtomTy->isAtomicType()) {
636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
637 << Ptr->getType() << Ptr->getSourceRange();
638 return ExprError();
639 }
640 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000641 }
Eli Friedman276b0612011-10-11 02:20:01 +0000642
Richard Smithff34d402012-04-12 05:08:17 +0000643 // For an arithmetic operation, the implied arithmetic must be well-formed.
644 if (Form == Arithmetic) {
645 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
646 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
648 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
649 return ExprError();
650 }
651 if (!IsAddSub && !ValType->isIntegerType()) {
652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
653 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
654 return ExprError();
655 }
656 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
657 // For __atomic_*_n operations, the value type must be a scalar integral or
658 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000659 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000660 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
661 return ExprError();
662 }
663
664 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
665 // For GNU atomics, require a trivially-copyable type. This is not part of
666 // the GNU atomics specification, but we enforce it for sanity.
667 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000668 << Ptr->getType() << Ptr->getSourceRange();
669 return ExprError();
670 }
671
Richard Smithff34d402012-04-12 05:08:17 +0000672 // FIXME: For any builtin other than a load, the ValType must not be
673 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000674
675 switch (ValType.getObjCLifetime()) {
676 case Qualifiers::OCL_None:
677 case Qualifiers::OCL_ExplicitNone:
678 // okay
679 break;
680
681 case Qualifiers::OCL_Weak:
682 case Qualifiers::OCL_Strong:
683 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000684 // FIXME: Can this happen? By this point, ValType should be known
685 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000686 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
687 << ValType << Ptr->getSourceRange();
688 return ExprError();
689 }
690
691 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000692 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000693 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000694 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000695 ResultType = Context.BoolTy;
696
Richard Smithff34d402012-04-12 05:08:17 +0000697 // The type of a parameter passed 'by value'. In the GNU atomics, such
698 // arguments are actually passed as pointers.
699 QualType ByValType = ValType; // 'CP'
700 if (!IsC11 && !IsN)
701 ByValType = Ptr->getType();
702
Eli Friedman276b0612011-10-11 02:20:01 +0000703 // The first argument --- the pointer --- has a fixed type; we
704 // deduce the types of the rest of the arguments accordingly. Walk
705 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000706 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000707 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000708 if (i < NumVals[Form] + 1) {
709 switch (i) {
710 case 1:
711 // The second argument is the non-atomic operand. For arithmetic, this
712 // is always passed by value, and for a compare_exchange it is always
713 // passed by address. For the rest, GNU uses by-address and C11 uses
714 // by-value.
715 assert(Form != Load);
716 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
717 Ty = ValType;
718 else if (Form == Copy || Form == Xchg)
719 Ty = ByValType;
720 else if (Form == Arithmetic)
721 Ty = Context.getPointerDiffType();
722 else
723 Ty = Context.getPointerType(ValType.getUnqualifiedType());
724 break;
725 case 2:
726 // The third argument to compare_exchange / GNU exchange is a
727 // (pointer to a) desired value.
728 Ty = ByValType;
729 break;
730 case 3:
731 // The fourth argument to GNU compare_exchange is a 'weak' flag.
732 Ty = Context.BoolTy;
733 break;
734 }
Eli Friedman276b0612011-10-11 02:20:01 +0000735 } else {
736 // The order(s) are always converted to int.
737 Ty = Context.IntTy;
738 }
Richard Smithff34d402012-04-12 05:08:17 +0000739
Eli Friedman276b0612011-10-11 02:20:01 +0000740 InitializedEntity Entity =
741 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000742 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000743 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
744 if (Arg.isInvalid())
745 return true;
746 TheCall->setArg(i, Arg.get());
747 }
748
Richard Smithff34d402012-04-12 05:08:17 +0000749 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000750 SmallVector<Expr*, 5> SubExprs;
751 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000752 switch (Form) {
753 case Init:
754 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000755 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000756 break;
757 case Load:
758 SubExprs.push_back(TheCall->getArg(1)); // Order
759 break;
760 case Copy:
761 case Arithmetic:
762 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000763 SubExprs.push_back(TheCall->getArg(2)); // Order
764 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000765 break;
766 case GNUXchg:
767 // Note, AtomicExpr::getVal2() has a special case for this atomic.
768 SubExprs.push_back(TheCall->getArg(3)); // Order
769 SubExprs.push_back(TheCall->getArg(1)); // Val1
770 SubExprs.push_back(TheCall->getArg(2)); // Val2
771 break;
772 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000773 SubExprs.push_back(TheCall->getArg(3)); // Order
774 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000775 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000776 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000777 break;
778 case GNUCmpXchg:
779 SubExprs.push_back(TheCall->getArg(4)); // Order
780 SubExprs.push_back(TheCall->getArg(1)); // Val1
781 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
782 SubExprs.push_back(TheCall->getArg(2)); // Val2
783 SubExprs.push_back(TheCall->getArg(3)); // Weak
784 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000785 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000786
787 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
788 SubExprs.data(), SubExprs.size(),
789 ResultType, Op,
790 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000791}
792
793
John McCall5f8d6042011-08-27 01:09:30 +0000794/// checkBuiltinArgument - Given a call to a builtin function, perform
795/// normal type-checking on the given argument, updating the call in
796/// place. This is useful when a builtin function requires custom
797/// type-checking for some of its arguments but not necessarily all of
798/// them.
799///
800/// Returns true on error.
801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
802 FunctionDecl *Fn = E->getDirectCallee();
803 assert(Fn && "builtin call without direct callee!");
804
805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
806 InitializedEntity Entity =
807 InitializedEntity::InitializeParameter(S.Context, Param);
808
809 ExprResult Arg = E->getArg(0);
810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
811 if (Arg.isInvalid())
812 return true;
813
814 E->setArg(ArgIndex, Arg.take());
815 return false;
816}
817
Chris Lattner5caa3702009-05-08 06:58:22 +0000818/// SemaBuiltinAtomicOverloaded - We have a call to a function like
819/// __sync_fetch_and_add, which is an overloaded function based on the pointer
820/// type of its first argument. The main ActOnCallExpr routines have already
821/// promoted the types of arguments because all of these calls are prototyped as
822/// void(...).
823///
824/// This function goes through and does final semantic checking for these
825/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000826ExprResult
827Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000828 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
831
832 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000833 if (TheCall->getNumArgs() < 1) {
834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835 << 0 << 1 << TheCall->getNumArgs()
836 << TheCall->getCallee()->getSourceRange();
837 return ExprError();
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner5caa3702009-05-08 06:58:22 +0000840 // Inspect the first argument of the atomic builtin. This should always be
841 // a pointer type, whose element is an integral scalar or pointer type.
842 // Because it is a pointer type, we don't have to worry about any implicit
843 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000844 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000845 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
847 if (FirstArgResult.isInvalid())
848 return ExprError();
849 FirstArg = FirstArgResult.take();
850 TheCall->setArg(0, FirstArg);
851
John McCallf85e1932011-06-15 23:02:42 +0000852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
853 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
855 << FirstArg->getType() << FirstArg->getSourceRange();
856 return ExprError();
857 }
Mike Stump1eb44332009-09-09 15:08:12 +0000858
John McCallf85e1932011-06-15 23:02:42 +0000859 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000861 !ValType->isBlockPointerType()) {
862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
863 << FirstArg->getType() << FirstArg->getSourceRange();
864 return ExprError();
865 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000866
John McCallf85e1932011-06-15 23:02:42 +0000867 switch (ValType.getObjCLifetime()) {
868 case Qualifiers::OCL_None:
869 case Qualifiers::OCL_ExplicitNone:
870 // okay
871 break;
872
873 case Qualifiers::OCL_Weak:
874 case Qualifiers::OCL_Strong:
875 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000876 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000877 << ValType << FirstArg->getSourceRange();
878 return ExprError();
879 }
880
John McCallb45ae252011-10-05 07:41:44 +0000881 // Strip any qualifiers off ValType.
882 ValType = ValType.getUnqualifiedType();
883
Chandler Carruth8d13d222010-07-18 20:54:12 +0000884 // The majority of builtins return a value, but a few have special return
885 // types, so allow them to override appropriately below.
886 QualType ResultType = ValType;
887
Chris Lattner5caa3702009-05-08 06:58:22 +0000888 // We need to figure out which concrete builtin this maps onto. For example,
889 // __sync_fetch_and_add with a 2 byte object turns into
890 // __sync_fetch_and_add_2.
891#define BUILTIN_ROW(x) \
892 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
893 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner5caa3702009-05-08 06:58:22 +0000895 static const unsigned BuiltinIndices[][5] = {
896 BUILTIN_ROW(__sync_fetch_and_add),
897 BUILTIN_ROW(__sync_fetch_and_sub),
898 BUILTIN_ROW(__sync_fetch_and_or),
899 BUILTIN_ROW(__sync_fetch_and_and),
900 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner5caa3702009-05-08 06:58:22 +0000902 BUILTIN_ROW(__sync_add_and_fetch),
903 BUILTIN_ROW(__sync_sub_and_fetch),
904 BUILTIN_ROW(__sync_and_and_fetch),
905 BUILTIN_ROW(__sync_or_and_fetch),
906 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Chris Lattner5caa3702009-05-08 06:58:22 +0000908 BUILTIN_ROW(__sync_val_compare_and_swap),
909 BUILTIN_ROW(__sync_bool_compare_and_swap),
910 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000911 BUILTIN_ROW(__sync_lock_release),
912 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000913 };
Mike Stump1eb44332009-09-09 15:08:12 +0000914#undef BUILTIN_ROW
915
Chris Lattner5caa3702009-05-08 06:58:22 +0000916 // Determine the index of the size.
917 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000918 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000919 case 1: SizeIndex = 0; break;
920 case 2: SizeIndex = 1; break;
921 case 4: SizeIndex = 2; break;
922 case 8: SizeIndex = 3; break;
923 case 16: SizeIndex = 4; break;
924 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000925 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
926 << FirstArg->getType() << FirstArg->getSourceRange();
927 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Chris Lattner5caa3702009-05-08 06:58:22 +0000930 // Each of these builtins has one pointer argument, followed by some number of
931 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
932 // that we ignore. Find out which row of BuiltinIndices to read from as well
933 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000934 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000935 unsigned BuiltinIndex, NumFixed = 1;
936 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000937 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000938 case Builtin::BI__sync_fetch_and_add:
939 case Builtin::BI__sync_fetch_and_add_1:
940 case Builtin::BI__sync_fetch_and_add_2:
941 case Builtin::BI__sync_fetch_and_add_4:
942 case Builtin::BI__sync_fetch_and_add_8:
943 case Builtin::BI__sync_fetch_and_add_16:
944 BuiltinIndex = 0;
945 break;
946
947 case Builtin::BI__sync_fetch_and_sub:
948 case Builtin::BI__sync_fetch_and_sub_1:
949 case Builtin::BI__sync_fetch_and_sub_2:
950 case Builtin::BI__sync_fetch_and_sub_4:
951 case Builtin::BI__sync_fetch_and_sub_8:
952 case Builtin::BI__sync_fetch_and_sub_16:
953 BuiltinIndex = 1;
954 break;
955
956 case Builtin::BI__sync_fetch_and_or:
957 case Builtin::BI__sync_fetch_and_or_1:
958 case Builtin::BI__sync_fetch_and_or_2:
959 case Builtin::BI__sync_fetch_and_or_4:
960 case Builtin::BI__sync_fetch_and_or_8:
961 case Builtin::BI__sync_fetch_and_or_16:
962 BuiltinIndex = 2;
963 break;
964
965 case Builtin::BI__sync_fetch_and_and:
966 case Builtin::BI__sync_fetch_and_and_1:
967 case Builtin::BI__sync_fetch_and_and_2:
968 case Builtin::BI__sync_fetch_and_and_4:
969 case Builtin::BI__sync_fetch_and_and_8:
970 case Builtin::BI__sync_fetch_and_and_16:
971 BuiltinIndex = 3;
972 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregora9766412011-11-28 16:30:08 +0000974 case Builtin::BI__sync_fetch_and_xor:
975 case Builtin::BI__sync_fetch_and_xor_1:
976 case Builtin::BI__sync_fetch_and_xor_2:
977 case Builtin::BI__sync_fetch_and_xor_4:
978 case Builtin::BI__sync_fetch_and_xor_8:
979 case Builtin::BI__sync_fetch_and_xor_16:
980 BuiltinIndex = 4;
981 break;
982
983 case Builtin::BI__sync_add_and_fetch:
984 case Builtin::BI__sync_add_and_fetch_1:
985 case Builtin::BI__sync_add_and_fetch_2:
986 case Builtin::BI__sync_add_and_fetch_4:
987 case Builtin::BI__sync_add_and_fetch_8:
988 case Builtin::BI__sync_add_and_fetch_16:
989 BuiltinIndex = 5;
990 break;
991
992 case Builtin::BI__sync_sub_and_fetch:
993 case Builtin::BI__sync_sub_and_fetch_1:
994 case Builtin::BI__sync_sub_and_fetch_2:
995 case Builtin::BI__sync_sub_and_fetch_4:
996 case Builtin::BI__sync_sub_and_fetch_8:
997 case Builtin::BI__sync_sub_and_fetch_16:
998 BuiltinIndex = 6;
999 break;
1000
1001 case Builtin::BI__sync_and_and_fetch:
1002 case Builtin::BI__sync_and_and_fetch_1:
1003 case Builtin::BI__sync_and_and_fetch_2:
1004 case Builtin::BI__sync_and_and_fetch_4:
1005 case Builtin::BI__sync_and_and_fetch_8:
1006 case Builtin::BI__sync_and_and_fetch_16:
1007 BuiltinIndex = 7;
1008 break;
1009
1010 case Builtin::BI__sync_or_and_fetch:
1011 case Builtin::BI__sync_or_and_fetch_1:
1012 case Builtin::BI__sync_or_and_fetch_2:
1013 case Builtin::BI__sync_or_and_fetch_4:
1014 case Builtin::BI__sync_or_and_fetch_8:
1015 case Builtin::BI__sync_or_and_fetch_16:
1016 BuiltinIndex = 8;
1017 break;
1018
1019 case Builtin::BI__sync_xor_and_fetch:
1020 case Builtin::BI__sync_xor_and_fetch_1:
1021 case Builtin::BI__sync_xor_and_fetch_2:
1022 case Builtin::BI__sync_xor_and_fetch_4:
1023 case Builtin::BI__sync_xor_and_fetch_8:
1024 case Builtin::BI__sync_xor_and_fetch_16:
1025 BuiltinIndex = 9;
1026 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner5caa3702009-05-08 06:58:22 +00001028 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001029 case Builtin::BI__sync_val_compare_and_swap_1:
1030 case Builtin::BI__sync_val_compare_and_swap_2:
1031 case Builtin::BI__sync_val_compare_and_swap_4:
1032 case Builtin::BI__sync_val_compare_and_swap_8:
1033 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001034 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001035 NumFixed = 2;
1036 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001037
Chris Lattner5caa3702009-05-08 06:58:22 +00001038 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001039 case Builtin::BI__sync_bool_compare_and_swap_1:
1040 case Builtin::BI__sync_bool_compare_and_swap_2:
1041 case Builtin::BI__sync_bool_compare_and_swap_4:
1042 case Builtin::BI__sync_bool_compare_and_swap_8:
1043 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001044 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001045 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001046 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001047 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001048
1049 case Builtin::BI__sync_lock_test_and_set:
1050 case Builtin::BI__sync_lock_test_and_set_1:
1051 case Builtin::BI__sync_lock_test_and_set_2:
1052 case Builtin::BI__sync_lock_test_and_set_4:
1053 case Builtin::BI__sync_lock_test_and_set_8:
1054 case Builtin::BI__sync_lock_test_and_set_16:
1055 BuiltinIndex = 12;
1056 break;
1057
Chris Lattner5caa3702009-05-08 06:58:22 +00001058 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001059 case Builtin::BI__sync_lock_release_1:
1060 case Builtin::BI__sync_lock_release_2:
1061 case Builtin::BI__sync_lock_release_4:
1062 case Builtin::BI__sync_lock_release_8:
1063 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001064 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001065 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001066 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001067 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001068
1069 case Builtin::BI__sync_swap:
1070 case Builtin::BI__sync_swap_1:
1071 case Builtin::BI__sync_swap_2:
1072 case Builtin::BI__sync_swap_4:
1073 case Builtin::BI__sync_swap_8:
1074 case Builtin::BI__sync_swap_16:
1075 BuiltinIndex = 14;
1076 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner5caa3702009-05-08 06:58:22 +00001079 // Now that we know how many fixed arguments we expect, first check that we
1080 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001081 if (TheCall->getNumArgs() < 1+NumFixed) {
1082 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1083 << 0 << 1+NumFixed << TheCall->getNumArgs()
1084 << TheCall->getCallee()->getSourceRange();
1085 return ExprError();
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001088 // Get the decl for the concrete builtin from this, we can tell what the
1089 // concrete integer type we should convert to is.
1090 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1091 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1092 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001093 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001094 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1095 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001096
John McCallf871d0c2010-08-07 06:22:56 +00001097 // The first argument --- the pointer --- has a fixed type; we
1098 // deduce the types of the rest of the arguments accordingly. Walk
1099 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001100 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001101 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Chris Lattner5caa3702009-05-08 06:58:22 +00001103 // GCC does an implicit conversion to the pointer or integer ValType. This
1104 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001105 // Initialize the argument.
1106 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1107 ValType, /*consume*/ false);
1108 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001109 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001110 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chris Lattner5caa3702009-05-08 06:58:22 +00001112 // Okay, we have something that *can* be converted to the right type. Check
1113 // to see if there is a potentially weird extension going on here. This can
1114 // happen when you do an atomic operation on something like an char* and
1115 // pass in 42. The 42 gets converted to char. This is even more strange
1116 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001117 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001118 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001121 ASTContext& Context = this->getASTContext();
1122
1123 // Create a new DeclRefExpr to refer to the new decl.
1124 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1125 Context,
1126 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001127 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001128 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001129 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001130 DRE->getLocation(),
1131 NewBuiltinDecl->getType(),
1132 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Chris Lattner5caa3702009-05-08 06:58:22 +00001134 // Set the callee in the CallExpr.
1135 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001136 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001137 if (PromotedCall.isInvalid())
1138 return ExprError();
1139 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001141 // Change the result type of the call to match the original value type. This
1142 // is arbitrary, but the codegen for these builtins ins design to handle it
1143 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001144 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001145
1146 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001147}
1148
Chris Lattner69039812009-02-18 06:01:06 +00001149/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001150/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001151/// Note: It might also make sense to do the UTF-16 conversion here (would
1152/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001153bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001154 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001155 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1156
Douglas Gregor5cee1192011-07-27 05:40:30 +00001157 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1159 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001160 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001163 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001164 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001165 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001166 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001167 const UTF8 *FromPtr = (UTF8 *)String.data();
1168 UTF16 *ToPtr = &ToBuf[0];
1169
1170 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1171 &ToPtr, ToPtr + NumBytes,
1172 strictConversion);
1173 // Check for conversion failure.
1174 if (Result != conversionOK)
1175 Diag(Arg->getLocStart(),
1176 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1177 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001178 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001179}
1180
Chris Lattnerc27c6652007-12-20 00:05:45 +00001181/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1182/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001183bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1184 Expr *Fn = TheCall->getCallee();
1185 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001186 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001187 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001188 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1189 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001190 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001191 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001192 return true;
1193 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001194
1195 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001196 return Diag(TheCall->getLocEnd(),
1197 diag::err_typecheck_call_too_few_args_at_least)
1198 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001199 }
1200
John McCall5f8d6042011-08-27 01:09:30 +00001201 // Type-check the first argument normally.
1202 if (checkBuiltinArgument(*this, TheCall, 0))
1203 return true;
1204
Chris Lattnerc27c6652007-12-20 00:05:45 +00001205 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001206 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001207 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001208 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001209 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001210 else if (FunctionDecl *FD = getCurFunctionDecl())
1211 isVariadic = FD->isVariadic();
1212 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001213 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Chris Lattnerc27c6652007-12-20 00:05:45 +00001215 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001216 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1217 return true;
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner30ce3442007-12-19 23:59:04 +00001220 // Verify that the second argument to the builtin is the last argument of the
1221 // current function or method.
1222 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001223 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Anders Carlsson88cf2262008-02-11 04:20:54 +00001225 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1226 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001227 // FIXME: This isn't correct for methods (results in bogus warning).
1228 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001229 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001230 if (CurBlock)
1231 LastArg = *(CurBlock->TheDecl->param_end()-1);
1232 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001233 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001234 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001235 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001236 SecondArgIsLastNamedArgument = PV == LastArg;
1237 }
1238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chris Lattner30ce3442007-12-19 23:59:04 +00001240 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001241 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001242 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1243 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001244}
Chris Lattner30ce3442007-12-19 23:59:04 +00001245
Chris Lattner1b9a0792007-12-20 00:26:33 +00001246/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1247/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001248bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1249 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001250 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001251 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001252 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001253 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001254 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001255 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001256 << SourceRange(TheCall->getArg(2)->getLocStart(),
1257 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001258
John Wiegley429bb272011-04-08 18:41:53 +00001259 ExprResult OrigArg0 = TheCall->getArg(0);
1260 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001261
Chris Lattner1b9a0792007-12-20 00:26:33 +00001262 // Do standard promotions between the two arguments, returning their common
1263 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001264 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001265 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1266 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001267
1268 // Make sure any conversions are pushed back into the call; this is
1269 // type safe since unordered compare builtins are declared as "_Bool
1270 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001271 TheCall->setArg(0, OrigArg0.get());
1272 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001273
John Wiegley429bb272011-04-08 18:41:53 +00001274 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001275 return false;
1276
Chris Lattner1b9a0792007-12-20 00:26:33 +00001277 // If the common type isn't a real floating type, then the arguments were
1278 // invalid for this operation.
1279 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001280 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001281 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001282 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1283 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner1b9a0792007-12-20 00:26:33 +00001285 return false;
1286}
1287
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001288/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1289/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001290/// to check everything. We expect the last argument to be a floating point
1291/// value.
1292bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1293 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001294 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001295 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001296 if (TheCall->getNumArgs() > NumArgs)
1297 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001298 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001299 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001300 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001301 (*(TheCall->arg_end()-1))->getLocEnd());
1302
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001303 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Eli Friedman9ac6f622009-08-31 20:06:00 +00001305 if (OrigArg->isTypeDependent())
1306 return false;
1307
Chris Lattner81368fb2010-05-06 05:50:07 +00001308 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001309 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001310 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001311 diag::err_typecheck_call_invalid_unary_fp)
1312 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattner81368fb2010-05-06 05:50:07 +00001314 // If this is an implicit conversion from float -> double, remove it.
1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1316 Expr *CastArg = Cast->getSubExpr();
1317 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1318 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1319 "promotion from float to double is the only expected cast here");
1320 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001321 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001322 }
1323 }
1324
Eli Friedman9ac6f622009-08-31 20:06:00 +00001325 return false;
1326}
1327
Eli Friedmand38617c2008-05-14 19:38:39 +00001328/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1329// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001330ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001331 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001332 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001333 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001334 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001335 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001336
Nate Begeman37b6a572010-06-08 00:16:34 +00001337 // Determine which of the following types of shufflevector we're checking:
1338 // 1) unary, vector mask: (lhs, mask)
1339 // 2) binary, vector mask: (lhs, rhs, mask)
1340 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1341 QualType resType = TheCall->getArg(0)->getType();
1342 unsigned numElements = 0;
1343
Douglas Gregorcde01732009-05-19 22:10:17 +00001344 if (!TheCall->getArg(0)->isTypeDependent() &&
1345 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001346 QualType LHSType = TheCall->getArg(0)->getType();
1347 QualType RHSType = TheCall->getArg(1)->getType();
1348
1349 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001350 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001351 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001352 TheCall->getArg(1)->getLocEnd());
1353 return ExprError();
1354 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001355
1356 numElements = LHSType->getAs<VectorType>()->getNumElements();
1357 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Nate Begeman37b6a572010-06-08 00:16:34 +00001359 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1360 // with mask. If so, verify that RHS is an integer vector type with the
1361 // same number of elts as lhs.
1362 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001363 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001364 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1365 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1366 << SourceRange(TheCall->getArg(1)->getLocStart(),
1367 TheCall->getArg(1)->getLocEnd());
1368 numResElements = numElements;
1369 }
1370 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001371 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001372 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001373 TheCall->getArg(1)->getLocEnd());
1374 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001375 } else if (numElements != numResElements) {
1376 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001377 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001378 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001379 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001380 }
1381
1382 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001383 if (TheCall->getArg(i)->isTypeDependent() ||
1384 TheCall->getArg(i)->isValueDependent())
1385 continue;
1386
Nate Begeman37b6a572010-06-08 00:16:34 +00001387 llvm::APSInt Result(32);
1388 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1389 return ExprError(Diag(TheCall->getLocStart(),
1390 diag::err_shufflevector_nonconstant_argument)
1391 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001392
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001393 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001394 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001395 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001396 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001397 }
1398
Chris Lattner5f9e2722011-07-23 10:55:15 +00001399 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001400
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001401 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001402 exprs.push_back(TheCall->getArg(i));
1403 TheCall->setArg(i, 0);
1404 }
1405
Nate Begemana88dc302009-08-12 02:10:25 +00001406 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001407 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001408 TheCall->getCallee()->getLocStart(),
1409 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001410}
Chris Lattner30ce3442007-12-19 23:59:04 +00001411
Daniel Dunbar4493f792008-07-21 22:59:13 +00001412/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1413// This is declared to take (const void*, ...) and can take two
1414// optional constant int args.
1415bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001416 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001417
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001418 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001419 return Diag(TheCall->getLocEnd(),
1420 diag::err_typecheck_call_too_many_args_at_most)
1421 << 0 /*function call*/ << 3 << NumArgs
1422 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001423
1424 // Argument 0 is checked for us and the remaining arguments must be
1425 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001426 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001427 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001428
Eli Friedman9aef7262009-12-04 00:30:06 +00001429 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001430 if (SemaBuiltinConstantArg(TheCall, i, Result))
1431 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Daniel Dunbar4493f792008-07-21 22:59:13 +00001433 // FIXME: gcc issues a warning and rewrites these to 0. These
1434 // seems especially odd for the third argument since the default
1435 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001436 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001437 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001438 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001439 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001440 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001441 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001443 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001444 }
1445 }
1446
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001447 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001448}
1449
Eric Christopher691ebc32010-04-17 02:26:23 +00001450/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1451/// TheCall is a constant expression.
1452bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1453 llvm::APSInt &Result) {
1454 Expr *Arg = TheCall->getArg(ArgNum);
1455 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1456 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1457
1458 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1459
1460 if (!Arg->isIntegerConstantExpr(Result, Context))
1461 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001462 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001463
Chris Lattner21fb98e2009-09-23 06:06:36 +00001464 return false;
1465}
1466
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001467/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1468/// int type). This simply type checks that type is one of the defined
1469/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001470// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001471bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001472 llvm::APSInt Result;
1473
1474 // Check constant-ness first.
1475 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1476 return true;
1477
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001478 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001479 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001480 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1481 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001482 }
1483
1484 return false;
1485}
1486
Eli Friedman586d6a82009-05-03 06:04:26 +00001487/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001488/// This checks that val is a constant 1.
1489bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1490 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001491 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001492
Eric Christopher691ebc32010-04-17 02:26:23 +00001493 // TODO: This is less than ideal. Overload this to take a value.
1494 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1495 return true;
1496
1497 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001498 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1499 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1500
1501 return false;
1502}
1503
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001504// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001505bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1506 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001507 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001508 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001509 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001510 if (E->isTypeDependent() || E->isValueDependent())
1511 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001512
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001513 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001514
David Blaikiea73cdcb2012-02-10 21:07:25 +00001515 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1516 // Technically -Wformat-nonliteral does not warn about this case.
1517 // The behavior of printf and friends in this case is implementation
1518 // dependent. Ideally if the format string cannot be null then
1519 // it should have a 'nonnull' attribute in the function prototype.
1520 return true;
1521
Ted Kremenekd30ef872009-01-12 23:09:09 +00001522 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001523 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001524 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001525 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001526 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001527 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001528 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001529 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1530 format_idx, firstDataArg, Type,
1531 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001532 }
1533
1534 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001535 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1536 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001537 }
1538
John McCall56ca35d2011-02-17 10:25:35 +00001539 case Stmt::OpaqueValueExprClass:
1540 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1541 E = src;
1542 goto tryAgain;
1543 }
1544 return false;
1545
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001546 case Stmt::PredefinedExprClass:
1547 // While __func__, etc., are technically not string literals, they
1548 // cannot contain format specifiers and thus are not a security
1549 // liability.
1550 return true;
1551
Ted Kremenek082d9362009-03-20 21:35:28 +00001552 case Stmt::DeclRefExprClass: {
1553 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Ted Kremenek082d9362009-03-20 21:35:28 +00001555 // As an exception, do not flag errors for variables binding to
1556 // const string literals.
1557 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1558 bool isConstant = false;
1559 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001560
Ted Kremenek082d9362009-03-20 21:35:28 +00001561 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1562 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001563 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001564 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001565 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001566 } else if (T->isObjCObjectPointerType()) {
1567 // In ObjC, there is usually no "const ObjectPointer" type,
1568 // so don't check if the pointee type is constant.
1569 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Ted Kremenek082d9362009-03-20 21:35:28 +00001572 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001573 if (const Expr *Init = VD->getAnyInitializer()) {
1574 // Look through initializers like const char c[] = { "foo" }
1575 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1576 if (InitList->isStringLiteralInit())
1577 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1578 }
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001579 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001580 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001581 Type, /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001582 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Anders Carlssond966a552009-06-28 19:55:58 +00001585 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1586 // special check to see if the format string is a function parameter
1587 // of the function calling the printf function. If the function
1588 // has an attribute indicating it is a printf-like function, then we
1589 // should suppress warnings concerning non-literals being used in a call
1590 // to a vprintf function. For example:
1591 //
1592 // void
1593 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1594 // va_list ap;
1595 // va_start(ap, fmt);
1596 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1597 // ...
1598 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001599 if (HasVAListArg) {
1600 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1601 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1602 int PVIndex = PV->getFunctionScopeIndex() + 1;
1603 for (specific_attr_iterator<FormatAttr>
1604 i = ND->specific_attr_begin<FormatAttr>(),
1605 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1606 FormatAttr *PVFormat = *i;
1607 // adjust for implicit parameter
1608 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1609 if (MD->isInstance())
1610 ++PVIndex;
1611 // We also check if the formats are compatible.
1612 // We can't pass a 'scanf' string to a 'printf' function.
1613 if (PVIndex == PVFormat->getFormatIdx() &&
1614 Type == GetFormatStringType(PVFormat))
1615 return true;
1616 }
1617 }
1618 }
1619 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Ted Kremenek082d9362009-03-20 21:35:28 +00001622 return false;
1623 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001624
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001625 case Stmt::CallExprClass:
1626 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001627 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001628 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1629 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1630 unsigned ArgIndex = FA->getFormatIdx();
1631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1632 if (MD->isInstance())
1633 --ArgIndex;
1634 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001636 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1637 format_idx, firstDataArg, Type,
1638 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlsson8f031b32009-06-27 04:05:33 +00001642 return false;
1643 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001644 case Stmt::ObjCStringLiteralClass:
1645 case Stmt::StringLiteralClass: {
1646 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Ted Kremenek082d9362009-03-20 21:35:28 +00001648 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001649 StrE = ObjCFExpr->getString();
1650 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001651 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Ted Kremenekd30ef872009-01-12 23:09:09 +00001653 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001654 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001655 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001656 return true;
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenekd30ef872009-01-12 23:09:09 +00001659 return false;
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Ted Kremenek082d9362009-03-20 21:35:28 +00001662 default:
1663 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001664 }
1665}
1666
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001667void
Mike Stump1eb44332009-09-09 15:08:12 +00001668Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001669 const Expr * const *ExprArgs,
1670 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001671 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1672 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001673 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001674 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001675 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001676 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001677 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001678 }
1679}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001680
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001681Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1682 return llvm::StringSwitch<FormatStringType>(Format->getType())
1683 .Case("scanf", FST_Scanf)
1684 .Cases("printf", "printf0", FST_Printf)
1685 .Cases("NSString", "CFString", FST_NSString)
1686 .Case("strftime", FST_Strftime)
1687 .Case("strfmon", FST_Strfmon)
1688 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1689 .Default(FST_Unknown);
1690}
1691
Ted Kremenek826a3452010-07-16 02:11:22 +00001692/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1693/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001694void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1695 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001696 // The way the format attribute works in GCC, the implicit this argument
1697 // of member functions is counted. However, it doesn't appear in our own
1698 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001699 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001700 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1701 IsCXXMember, TheCall->getRParenLoc(),
1702 TheCall->getCallee()->getSourceRange());
1703}
1704
1705void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1706 unsigned NumArgs, bool IsCXXMember,
1707 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001708 bool HasVAListArg = Format->getFirstArg() == 0;
1709 unsigned format_idx = Format->getFormatIdx() - 1;
1710 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1711 if (IsCXXMember) {
1712 if (format_idx == 0)
1713 return;
1714 --format_idx;
1715 if(firstDataArg != 0)
1716 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001717 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001718 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1719 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001720}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001721
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001722void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1723 bool HasVAListArg, unsigned format_idx,
1724 unsigned firstDataArg, FormatStringType Type,
1725 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001726 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001727 if (format_idx >= NumArgs) {
1728 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001729 return;
1730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001732 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattner59907c42007-08-10 20:18:51 +00001734 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001735 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001736 // Dynamically generated format strings are difficult to
1737 // automatically vet at compile time. Requiring that format strings
1738 // are string literals: (1) permits the checking of format strings by
1739 // the compiler and thereby (2) can practically remove the source of
1740 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001741
Mike Stump1eb44332009-09-09 15:08:12 +00001742 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001743 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001744 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001745 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001746 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001747 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001748 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001749
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001750 // Strftime is particular as it always uses a single 'time' argument,
1751 // so it is safe to pass a non-literal string.
1752 if (Type == FST_Strftime)
1753 return;
1754
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001755 // Do not emit diag when the string param is a macro expansion and the
1756 // format is either NSString or CFString. This is a hack to prevent
1757 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1758 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001759 if (Type == FST_NSString &&
1760 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001761 return;
1762
Chris Lattner655f1412009-04-29 04:59:47 +00001763 // If there are no arguments specified, warn with -Wformat-security, otherwise
1764 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001765 if (NumArgs == format_idx+1)
1766 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001767 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001768 << OrigFormatExpr->getSourceRange();
1769 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001770 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001771 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001772 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001773}
Ted Kremenek71895b92007-08-14 17:39:48 +00001774
Ted Kremeneke0e53132010-01-28 23:39:18 +00001775namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001776class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1777protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001778 Sema &S;
1779 const StringLiteral *FExpr;
1780 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001781 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001782 const unsigned NumDataArgs;
1783 const bool IsObjCLiteral;
1784 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001785 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001786 const Expr * const *Args;
1787 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001788 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001789 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001790 bool usesPositionalArgs;
1791 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001792 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001793public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001794 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001795 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001796 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001797 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001798 Expr **args, unsigned numArgs,
1799 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001800 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001801 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001802 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001803 IsObjCLiteral(isObjCLiteral), Beg(beg),
1804 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001805 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001806 usesPositionalArgs(false), atFirstArg(true),
1807 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001808 CoveredArgs.resize(numDataArgs);
1809 CoveredArgs.reset();
1810 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001811
Ted Kremenek07d161f2010-01-29 01:50:07 +00001812 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001813
Ted Kremenek826a3452010-07-16 02:11:22 +00001814 void HandleIncompleteSpecifier(const char *startSpecifier,
1815 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001816
1817 void HandleNonStandardLengthModifier(
1818 const analyze_format_string::LengthModifier &LM,
1819 const char *startSpecifier, unsigned specifierLen);
1820
1821 void HandleNonStandardConversionSpecifier(
1822 const analyze_format_string::ConversionSpecifier &CS,
1823 const char *startSpecifier, unsigned specifierLen);
1824
1825 void HandleNonStandardConversionSpecification(
1826 const analyze_format_string::LengthModifier &LM,
1827 const analyze_format_string::ConversionSpecifier &CS,
1828 const char *startSpecifier, unsigned specifierLen);
1829
Hans Wennborgf8562642012-03-09 10:10:54 +00001830 virtual void HandlePosition(const char *startPos, unsigned posLen);
1831
Ted Kremenekefaff192010-02-27 01:41:03 +00001832 virtual void HandleInvalidPosition(const char *startSpecifier,
1833 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001834 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001835
1836 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1837
Ted Kremeneke0e53132010-01-28 23:39:18 +00001838 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001839
Richard Trieu55733de2011-10-28 00:41:25 +00001840 template <typename Range>
1841 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1842 const Expr *ArgumentExpr,
1843 PartialDiagnostic PDiag,
1844 SourceLocation StringLoc,
1845 bool IsStringLocation, Range StringRange,
1846 FixItHint Fixit = FixItHint());
1847
Ted Kremenek826a3452010-07-16 02:11:22 +00001848protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001849 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1850 const char *startSpec,
1851 unsigned specifierLen,
1852 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001853
1854 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1855 const char *startSpec,
1856 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001857
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001858 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001859 CharSourceRange getSpecifierRange(const char *startSpecifier,
1860 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001861 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001862
Ted Kremenek0d277352010-01-29 01:06:55 +00001863 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001864
1865 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1866 const analyze_format_string::ConversionSpecifier &CS,
1867 const char *startSpecifier, unsigned specifierLen,
1868 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001869
1870 template <typename Range>
1871 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1872 bool IsStringLocation, Range StringRange,
1873 FixItHint Fixit = FixItHint());
1874
1875 void CheckPositionalAndNonpositionalArgs(
1876 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001877};
1878}
1879
Ted Kremenek826a3452010-07-16 02:11:22 +00001880SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001881 return OrigFormatExpr->getSourceRange();
1882}
1883
Ted Kremenek826a3452010-07-16 02:11:22 +00001884CharSourceRange CheckFormatHandler::
1885getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001886 SourceLocation Start = getLocationOfByte(startSpecifier);
1887 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1888
1889 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001890 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001891
1892 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001893}
1894
Ted Kremenek826a3452010-07-16 02:11:22 +00001895SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001896 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001897}
1898
Ted Kremenek826a3452010-07-16 02:11:22 +00001899void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1900 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001901 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1902 getLocationOfByte(startSpecifier),
1903 /*IsStringLocation*/true,
1904 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001905}
1906
Hans Wennborg76517422012-02-22 10:17:01 +00001907void CheckFormatHandler::HandleNonStandardLengthModifier(
1908 const analyze_format_string::LengthModifier &LM,
1909 const char *startSpecifier, unsigned specifierLen) {
1910 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001911 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001912 getLocationOfByte(LM.getStart()),
1913 /*IsStringLocation*/true,
1914 getSpecifierRange(startSpecifier, specifierLen));
1915}
1916
1917void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1918 const analyze_format_string::ConversionSpecifier &CS,
1919 const char *startSpecifier, unsigned specifierLen) {
1920 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001921 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001922 getLocationOfByte(CS.getStart()),
1923 /*IsStringLocation*/true,
1924 getSpecifierRange(startSpecifier, specifierLen));
1925}
1926
1927void CheckFormatHandler::HandleNonStandardConversionSpecification(
1928 const analyze_format_string::LengthModifier &LM,
1929 const analyze_format_string::ConversionSpecifier &CS,
1930 const char *startSpecifier, unsigned specifierLen) {
1931 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1932 << LM.toString() << CS.toString(),
1933 getLocationOfByte(LM.getStart()),
1934 /*IsStringLocation*/true,
1935 getSpecifierRange(startSpecifier, specifierLen));
1936}
1937
Hans Wennborgf8562642012-03-09 10:10:54 +00001938void CheckFormatHandler::HandlePosition(const char *startPos,
1939 unsigned posLen) {
1940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1941 getLocationOfByte(startPos),
1942 /*IsStringLocation*/true,
1943 getSpecifierRange(startPos, posLen));
1944}
1945
Ted Kremenekefaff192010-02-27 01:41:03 +00001946void
Ted Kremenek826a3452010-07-16 02:11:22 +00001947CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1948 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1950 << (unsigned) p,
1951 getLocationOfByte(startPos), /*IsStringLocation*/true,
1952 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001953}
1954
Ted Kremenek826a3452010-07-16 02:11:22 +00001955void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001956 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001957 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1958 getLocationOfByte(startPos),
1959 /*IsStringLocation*/true,
1960 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001961}
1962
Ted Kremenek826a3452010-07-16 02:11:22 +00001963void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001964 if (!IsObjCLiteral) {
1965 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001966 EmitFormatDiagnostic(
1967 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1968 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1969 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001970 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001971}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001972
Ted Kremenek826a3452010-07-16 02:11:22 +00001973const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001974 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001975}
1976
1977void CheckFormatHandler::DoneProcessing() {
1978 // Does the number of data arguments exceed the number of
1979 // format conversions in the format string?
1980 if (!HasVAListArg) {
1981 // Find any arguments that weren't covered.
1982 CoveredArgs.flip();
1983 signed notCoveredArg = CoveredArgs.find_first();
1984 if (notCoveredArg >= 0) {
1985 assert((unsigned)notCoveredArg < NumDataArgs);
Bob Wilsonc03f2df2012-05-03 19:47:19 +00001986 SourceLocation Loc = getDataArg((unsigned) notCoveredArg)->getLocStart();
1987 if (!S.getSourceManager().isInSystemMacro(Loc)) {
1988 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1989 Loc,
1990 /*IsStringLocation*/false, getFormatStringRange());
1991 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001992 }
1993 }
1994}
1995
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001996bool
1997CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1998 SourceLocation Loc,
1999 const char *startSpec,
2000 unsigned specifierLen,
2001 const char *csStart,
2002 unsigned csLen) {
2003
2004 bool keepGoing = true;
2005 if (argIndex < NumDataArgs) {
2006 // Consider the argument coverered, even though the specifier doesn't
2007 // make sense.
2008 CoveredArgs.set(argIndex);
2009 }
2010 else {
2011 // If argIndex exceeds the number of data arguments we
2012 // don't issue a warning because that is just a cascade of warnings (and
2013 // they may have intended '%%' anyway). We don't want to continue processing
2014 // the format string after this point, however, as we will like just get
2015 // gibberish when trying to match arguments.
2016 keepGoing = false;
2017 }
2018
Richard Trieu55733de2011-10-28 00:41:25 +00002019 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2020 << StringRef(csStart, csLen),
2021 Loc, /*IsStringLocation*/true,
2022 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002023
2024 return keepGoing;
2025}
2026
Richard Trieu55733de2011-10-28 00:41:25 +00002027void
2028CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2029 const char *startSpec,
2030 unsigned specifierLen) {
2031 EmitFormatDiagnostic(
2032 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2033 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2034}
2035
Ted Kremenek666a1972010-07-26 19:45:42 +00002036bool
2037CheckFormatHandler::CheckNumArgs(
2038 const analyze_format_string::FormatSpecifier &FS,
2039 const analyze_format_string::ConversionSpecifier &CS,
2040 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2041
2042 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002043 PartialDiagnostic PDiag = FS.usesPositionalArg()
2044 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2045 << (argIndex+1) << NumDataArgs)
2046 : S.PDiag(diag::warn_printf_insufficient_data_args);
2047 EmitFormatDiagnostic(
2048 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2049 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002050 return false;
2051 }
2052 return true;
2053}
2054
Richard Trieu55733de2011-10-28 00:41:25 +00002055template<typename Range>
2056void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2057 SourceLocation Loc,
2058 bool IsStringLocation,
2059 Range StringRange,
2060 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002061 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002062 Loc, IsStringLocation, StringRange, FixIt);
2063}
2064
2065/// \brief If the format string is not within the funcion call, emit a note
2066/// so that the function call and string are in diagnostic messages.
2067///
2068/// \param inFunctionCall if true, the format string is within the function
2069/// call and only one diagnostic message will be produced. Otherwise, an
2070/// extra note will be emitted pointing to location of the format string.
2071///
2072/// \param ArgumentExpr the expression that is passed as the format string
2073/// argument in the function call. Used for getting locations when two
2074/// diagnostics are emitted.
2075///
2076/// \param PDiag the callee should already have provided any strings for the
2077/// diagnostic message. This function only adds locations and fixits
2078/// to diagnostics.
2079///
2080/// \param Loc primary location for diagnostic. If two diagnostics are
2081/// required, one will be at Loc and a new SourceLocation will be created for
2082/// the other one.
2083///
2084/// \param IsStringLocation if true, Loc points to the format string should be
2085/// used for the note. Otherwise, Loc points to the argument list and will
2086/// be used with PDiag.
2087///
2088/// \param StringRange some or all of the string to highlight. This is
2089/// templated so it can accept either a CharSourceRange or a SourceRange.
2090///
2091/// \param Fixit optional fix it hint for the format string.
2092template<typename Range>
2093void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2094 const Expr *ArgumentExpr,
2095 PartialDiagnostic PDiag,
2096 SourceLocation Loc,
2097 bool IsStringLocation,
2098 Range StringRange,
2099 FixItHint FixIt) {
2100 if (InFunctionCall)
2101 S.Diag(Loc, PDiag) << StringRange << FixIt;
2102 else {
2103 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2104 << ArgumentExpr->getSourceRange();
2105 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2106 diag::note_format_string_defined)
2107 << StringRange << FixIt;
2108 }
2109}
2110
Ted Kremenek826a3452010-07-16 02:11:22 +00002111//===--- CHECK: Printf format string checking ------------------------------===//
2112
2113namespace {
2114class CheckPrintfHandler : public CheckFormatHandler {
2115public:
2116 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2117 const Expr *origFormatExpr, unsigned firstDataArg,
2118 unsigned numDataArgs, bool isObjCLiteral,
2119 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002120 Expr **Args, unsigned NumArgs,
2121 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002122 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2123 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002124 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002125
2126
2127 bool HandleInvalidPrintfConversionSpecifier(
2128 const analyze_printf::PrintfSpecifier &FS,
2129 const char *startSpecifier,
2130 unsigned specifierLen);
2131
2132 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2133 const char *startSpecifier,
2134 unsigned specifierLen);
2135
2136 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2137 const char *startSpecifier, unsigned specifierLen);
2138 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2139 const analyze_printf::OptionalAmount &Amt,
2140 unsigned type,
2141 const char *startSpecifier, unsigned specifierLen);
2142 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2143 const analyze_printf::OptionalFlag &flag,
2144 const char *startSpecifier, unsigned specifierLen);
2145 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2146 const analyze_printf::OptionalFlag &ignoredFlag,
2147 const analyze_printf::OptionalFlag &flag,
2148 const char *startSpecifier, unsigned specifierLen);
2149};
2150}
2151
2152bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2153 const analyze_printf::PrintfSpecifier &FS,
2154 const char *startSpecifier,
2155 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002156 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002157 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002158
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002159 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2160 getLocationOfByte(CS.getStart()),
2161 startSpecifier, specifierLen,
2162 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002163}
2164
Ted Kremenek826a3452010-07-16 02:11:22 +00002165bool CheckPrintfHandler::HandleAmount(
2166 const analyze_format_string::OptionalAmount &Amt,
2167 unsigned k, const char *startSpecifier,
2168 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002169
2170 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002171 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002172 unsigned argIndex = Amt.getArgIndex();
2173 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002174 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2175 << k,
2176 getLocationOfByte(Amt.getStart()),
2177 /*IsStringLocation*/true,
2178 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002179 // Don't do any more checking. We will just emit
2180 // spurious errors.
2181 return false;
2182 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002183
Ted Kremenek0d277352010-01-29 01:06:55 +00002184 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002185 // Although not in conformance with C99, we also allow the argument to be
2186 // an 'unsigned int' as that is a reasonably safe case. GCC also
2187 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002188 CoveredArgs.set(argIndex);
2189 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002190 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002191
2192 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2193 assert(ATR.isValid());
2194
2195 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002196 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002197 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002198 << T << Arg->getSourceRange(),
2199 getLocationOfByte(Amt.getStart()),
2200 /*IsStringLocation*/true,
2201 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002202 // Don't do any more checking. We will just emit
2203 // spurious errors.
2204 return false;
2205 }
2206 }
2207 }
2208 return true;
2209}
Ted Kremenek0d277352010-01-29 01:06:55 +00002210
Tom Caree4ee9662010-06-17 19:00:27 +00002211void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002212 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002213 const analyze_printf::OptionalAmount &Amt,
2214 unsigned type,
2215 const char *startSpecifier,
2216 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002217 const analyze_printf::PrintfConversionSpecifier &CS =
2218 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002219
Richard Trieu55733de2011-10-28 00:41:25 +00002220 FixItHint fixit =
2221 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2222 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2223 Amt.getConstantLength()))
2224 : FixItHint();
2225
2226 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2227 << type << CS.toString(),
2228 getLocationOfByte(Amt.getStart()),
2229 /*IsStringLocation*/true,
2230 getSpecifierRange(startSpecifier, specifierLen),
2231 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002232}
2233
Ted Kremenek826a3452010-07-16 02:11:22 +00002234void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002235 const analyze_printf::OptionalFlag &flag,
2236 const char *startSpecifier,
2237 unsigned specifierLen) {
2238 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002239 const analyze_printf::PrintfConversionSpecifier &CS =
2240 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002241 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2242 << flag.toString() << CS.toString(),
2243 getLocationOfByte(flag.getPosition()),
2244 /*IsStringLocation*/true,
2245 getSpecifierRange(startSpecifier, specifierLen),
2246 FixItHint::CreateRemoval(
2247 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002248}
2249
2250void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002251 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002252 const analyze_printf::OptionalFlag &ignoredFlag,
2253 const analyze_printf::OptionalFlag &flag,
2254 const char *startSpecifier,
2255 unsigned specifierLen) {
2256 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002257 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2258 << ignoredFlag.toString() << flag.toString(),
2259 getLocationOfByte(ignoredFlag.getPosition()),
2260 /*IsStringLocation*/true,
2261 getSpecifierRange(startSpecifier, specifierLen),
2262 FixItHint::CreateRemoval(
2263 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002264}
2265
Ted Kremeneke0e53132010-01-28 23:39:18 +00002266bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002267CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002268 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002269 const char *startSpecifier,
2270 unsigned specifierLen) {
2271
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002272 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002273 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002274 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002275
Ted Kremenekbaa40062010-07-19 22:01:06 +00002276 if (FS.consumesDataArgument()) {
2277 if (atFirstArg) {
2278 atFirstArg = false;
2279 usesPositionalArgs = FS.usesPositionalArg();
2280 }
2281 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002282 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2283 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002284 return false;
2285 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002286 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002287
Ted Kremenekefaff192010-02-27 01:41:03 +00002288 // First check if the field width, precision, and conversion specifier
2289 // have matching data arguments.
2290 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2291 startSpecifier, specifierLen)) {
2292 return false;
2293 }
2294
2295 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2296 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002297 return false;
2298 }
2299
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002300 if (!CS.consumesDataArgument()) {
2301 // FIXME: Technically specifying a precision or field width here
2302 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002303 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002304 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002305
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002306 // Consume the argument.
2307 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002308 if (argIndex < NumDataArgs) {
2309 // The check to see if the argIndex is valid will come later.
2310 // We set the bit here because we may exit early from this
2311 // function if we encounter some other error.
2312 CoveredArgs.set(argIndex);
2313 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002314
2315 // Check for using an Objective-C specific conversion specifier
2316 // in a non-ObjC literal.
2317 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002318 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2319 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002320 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002321
Tom Caree4ee9662010-06-17 19:00:27 +00002322 // Check for invalid use of field width
2323 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002324 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002325 startSpecifier, specifierLen);
2326 }
2327
2328 // Check for invalid use of precision
2329 if (!FS.hasValidPrecision()) {
2330 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2331 startSpecifier, specifierLen);
2332 }
2333
2334 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002335 if (!FS.hasValidThousandsGroupingPrefix())
2336 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002337 if (!FS.hasValidLeadingZeros())
2338 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2339 if (!FS.hasValidPlusPrefix())
2340 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002341 if (!FS.hasValidSpacePrefix())
2342 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002343 if (!FS.hasValidAlternativeForm())
2344 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2345 if (!FS.hasValidLeftJustified())
2346 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2347
2348 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002349 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2350 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2351 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002352 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2353 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2354 startSpecifier, specifierLen);
2355
2356 // Check the length modifier is valid with the given conversion specifier.
2357 const LengthModifier &LM = FS.getLengthModifier();
2358 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2360 << LM.toString() << CS.toString(),
2361 getLocationOfByte(LM.getStart()),
2362 /*IsStringLocation*/true,
2363 getSpecifierRange(startSpecifier, specifierLen),
2364 FixItHint::CreateRemoval(
2365 getSpecifierRange(LM.getStart(),
2366 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002367 if (!FS.hasStandardLengthModifier())
2368 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002369 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002370 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2371 if (!FS.hasStandardLengthConversionCombination())
2372 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2373 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002374
2375 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002376 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002377 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2379 getLocationOfByte(CS.getStart()),
2380 /*IsStringLocation*/true,
2381 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002382 // Continue checking the other format specifiers.
2383 return true;
2384 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002385
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002386 // The remaining checks depend on the data arguments.
2387 if (HasVAListArg)
2388 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002389
Ted Kremenek666a1972010-07-26 19:45:42 +00002390 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002391 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002392
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002393 // Now type check the data expression that matches the
2394 // format specifier.
2395 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002396 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2397 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002398 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2399 // Check if we didn't match because of an implicit cast from a 'char'
2400 // or 'short' to an 'int'. This is done because printf is a varargs
2401 // function.
2402 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
James Molloy392da482012-05-04 10:55:22 +00002403 if (ICE->getType() == S.Context.IntTy ||
2404 ICE->getType() == S.Context.UnsignedIntTy) {
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002405 // All further checking is done on the subexpression.
2406 Ex = ICE->getSubExpr();
2407 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002408 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002409 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002410
2411 // We may be able to offer a FixItHint if it is a supported type.
2412 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002413 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002414 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002415
2416 if (success) {
2417 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002418 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002419 llvm::raw_svector_ostream os(buf);
2420 fixedFS.toString(os);
2421
Richard Trieu55733de2011-10-28 00:41:25 +00002422 EmitFormatDiagnostic(
2423 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002424 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002425 << Ex->getSourceRange(),
2426 getLocationOfByte(CS.getStart()),
2427 /*IsStringLocation*/true,
2428 getSpecifierRange(startSpecifier, specifierLen),
2429 FixItHint::CreateReplacement(
2430 getSpecifierRange(startSpecifier, specifierLen),
2431 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002432 }
2433 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002434 EmitFormatDiagnostic(
2435 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2436 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2437 << getSpecifierRange(startSpecifier, specifierLen)
2438 << Ex->getSourceRange(),
2439 getLocationOfByte(CS.getStart()),
2440 true,
2441 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002442 }
2443 }
2444
Ted Kremeneke0e53132010-01-28 23:39:18 +00002445 return true;
2446}
2447
Ted Kremenek826a3452010-07-16 02:11:22 +00002448//===--- CHECK: Scanf format string checking ------------------------------===//
2449
2450namespace {
2451class CheckScanfHandler : public CheckFormatHandler {
2452public:
2453 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2454 const Expr *origFormatExpr, unsigned firstDataArg,
2455 unsigned numDataArgs, bool isObjCLiteral,
2456 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002457 Expr **Args, unsigned NumArgs,
2458 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002459 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2460 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002461 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002462
2463 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2464 const char *startSpecifier,
2465 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002466
2467 bool HandleInvalidScanfConversionSpecifier(
2468 const analyze_scanf::ScanfSpecifier &FS,
2469 const char *startSpecifier,
2470 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002471
2472 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002473};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002474}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002475
Ted Kremenekb7c21012010-07-16 18:28:03 +00002476void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2477 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002478 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2479 getLocationOfByte(end), /*IsStringLocation*/true,
2480 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002481}
2482
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002483bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2484 const analyze_scanf::ScanfSpecifier &FS,
2485 const char *startSpecifier,
2486 unsigned specifierLen) {
2487
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002488 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002489 FS.getConversionSpecifier();
2490
2491 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2492 getLocationOfByte(CS.getStart()),
2493 startSpecifier, specifierLen,
2494 CS.getStart(), CS.getLength());
2495}
2496
Ted Kremenek826a3452010-07-16 02:11:22 +00002497bool CheckScanfHandler::HandleScanfSpecifier(
2498 const analyze_scanf::ScanfSpecifier &FS,
2499 const char *startSpecifier,
2500 unsigned specifierLen) {
2501
2502 using namespace analyze_scanf;
2503 using namespace analyze_format_string;
2504
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002505 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002506
Ted Kremenekbaa40062010-07-19 22:01:06 +00002507 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2508 // be used to decide if we are using positional arguments consistently.
2509 if (FS.consumesDataArgument()) {
2510 if (atFirstArg) {
2511 atFirstArg = false;
2512 usesPositionalArgs = FS.usesPositionalArg();
2513 }
2514 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002515 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2516 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002517 return false;
2518 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002519 }
2520
2521 // Check if the field with is non-zero.
2522 const OptionalAmount &Amt = FS.getFieldWidth();
2523 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2524 if (Amt.getConstantAmount() == 0) {
2525 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2526 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002527 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2528 getLocationOfByte(Amt.getStart()),
2529 /*IsStringLocation*/true, R,
2530 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002531 }
2532 }
2533
2534 if (!FS.consumesDataArgument()) {
2535 // FIXME: Technically specifying a precision or field width here
2536 // makes no sense. Worth issuing a warning at some point.
2537 return true;
2538 }
2539
2540 // Consume the argument.
2541 unsigned argIndex = FS.getArgIndex();
2542 if (argIndex < NumDataArgs) {
2543 // The check to see if the argIndex is valid will come later.
2544 // We set the bit here because we may exit early from this
2545 // function if we encounter some other error.
2546 CoveredArgs.set(argIndex);
2547 }
2548
Ted Kremenek1e51c202010-07-20 20:04:47 +00002549 // Check the length modifier is valid with the given conversion specifier.
2550 const LengthModifier &LM = FS.getLengthModifier();
2551 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002552 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2554 << LM.toString() << CS.toString()
2555 << getSpecifierRange(startSpecifier, specifierLen),
2556 getLocationOfByte(LM.getStart()),
2557 /*IsStringLocation*/true, R,
2558 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002559 }
2560
Hans Wennborg76517422012-02-22 10:17:01 +00002561 if (!FS.hasStandardLengthModifier())
2562 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002563 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002564 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2565 if (!FS.hasStandardLengthConversionCombination())
2566 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2567 specifierLen);
2568
Ted Kremenek826a3452010-07-16 02:11:22 +00002569 // The remaining checks depend on the data arguments.
2570 if (HasVAListArg)
2571 return true;
2572
Ted Kremenek666a1972010-07-26 19:45:42 +00002573 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002574 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002575
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002576 // Check that the argument type matches the format specifier.
2577 const Expr *Ex = getDataArg(argIndex);
2578 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2579 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2580 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002581 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002582 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002583
2584 if (success) {
2585 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002586 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002587 llvm::raw_svector_ostream os(buf);
2588 fixedFS.toString(os);
2589
2590 EmitFormatDiagnostic(
2591 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2592 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2593 << Ex->getSourceRange(),
2594 getLocationOfByte(CS.getStart()),
2595 /*IsStringLocation*/true,
2596 getSpecifierRange(startSpecifier, specifierLen),
2597 FixItHint::CreateReplacement(
2598 getSpecifierRange(startSpecifier, specifierLen),
2599 os.str()));
2600 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002601 EmitFormatDiagnostic(
2602 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002603 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002604 << Ex->getSourceRange(),
2605 getLocationOfByte(CS.getStart()),
2606 /*IsStringLocation*/true,
2607 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002608 }
2609 }
2610
Ted Kremenek826a3452010-07-16 02:11:22 +00002611 return true;
2612}
2613
2614void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002615 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002616 Expr **Args, unsigned NumArgs,
2617 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002618 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002619 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002620
Ted Kremeneke0e53132010-01-28 23:39:18 +00002621 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002622 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002623 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002624 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002625 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2626 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002627 return;
2628 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002629
Ted Kremeneke0e53132010-01-28 23:39:18 +00002630 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002631 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002632 const char *Str = StrRef.data();
2633 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002634 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002635
Ted Kremeneke0e53132010-01-28 23:39:18 +00002636 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002637 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002638 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002639 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002640 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2641 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002642 return;
2643 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002644
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002645 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002646 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002647 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002648 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002649 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002650
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002651 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002652 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002653 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002654 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002655 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002656 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002657 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002658 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002659
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002660 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002661 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002662 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002663 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002664}
2665
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002666//===--- CHECK: Standard memory functions ---------------------------------===//
2667
Douglas Gregor2a053a32011-05-03 20:05:22 +00002668/// \brief Determine whether the given type is a dynamic class type (e.g.,
2669/// whether it has a vtable).
2670static bool isDynamicClassType(QualType T) {
2671 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2672 if (CXXRecordDecl *Definition = Record->getDefinition())
2673 if (Definition->isDynamicClass())
2674 return true;
2675
2676 return false;
2677}
2678
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002679/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002680/// otherwise returns NULL.
2681static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002682 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002683 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2684 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2685 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002686
Chandler Carruth000d4282011-06-16 09:09:40 +00002687 return 0;
2688}
2689
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002690/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002691static QualType getSizeOfArgType(const Expr* E) {
2692 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2693 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2694 if (SizeOf->getKind() == clang::UETT_SizeOf)
2695 return SizeOf->getTypeOfArgument();
2696
2697 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002698}
2699
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002700/// \brief Check for dangerous or invalid arguments to memset().
2701///
Chandler Carruth929f0132011-06-03 06:23:57 +00002702/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002703/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2704/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002705///
2706/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002707void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002708 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002709 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002710 assert(BId != 0);
2711
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002712 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002713 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002714 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002715 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002716 return;
2717
Anna Zaks0a151a12012-01-17 00:37:07 +00002718 unsigned LastArg = (BId == Builtin::BImemset ||
2719 BId == Builtin::BIstrndup ? 1 : 2);
2720 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002721 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002722
2723 // We have special checking when the length is a sizeof expression.
2724 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2725 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2726 llvm::FoldingSetNodeID SizeOfArgID;
2727
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002728 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2729 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002730 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002731
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002732 QualType DestTy = Dest->getType();
2733 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2734 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002735
Chandler Carruth000d4282011-06-16 09:09:40 +00002736 // Never warn about void type pointers. This can be used to suppress
2737 // false positives.
2738 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002739 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002740
Chandler Carruth000d4282011-06-16 09:09:40 +00002741 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2742 // actually comparing the expressions for equality. Because computing the
2743 // expression IDs can be expensive, we only do this if the diagnostic is
2744 // enabled.
2745 if (SizeOfArg &&
2746 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2747 SizeOfArg->getExprLoc())) {
2748 // We only compute IDs for expressions if the warning is enabled, and
2749 // cache the sizeof arg's ID.
2750 if (SizeOfArgID == llvm::FoldingSetNodeID())
2751 SizeOfArg->Profile(SizeOfArgID, Context, true);
2752 llvm::FoldingSetNodeID DestID;
2753 Dest->Profile(DestID, Context, true);
2754 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002755 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2756 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002757 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2758 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2759 if (UnaryOp->getOpcode() == UO_AddrOf)
2760 ActionIdx = 1; // If its an address-of operator, just remove it.
2761 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2762 ActionIdx = 2; // If the pointee's size is sizeof(char),
2763 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002764 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002765 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002766 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2767 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002768 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002769 << Dest->getSourceRange()
2770 << SizeOfArg->getSourceRange());
2771 break;
2772 }
2773 }
2774
2775 // Also check for cases where the sizeof argument is the exact same
2776 // type as the memory argument, and where it points to a user-defined
2777 // record type.
2778 if (SizeOfArgTy != QualType()) {
2779 if (PointeeTy->isRecordType() &&
2780 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2781 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2782 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2783 << FnName << SizeOfArgTy << ArgIdx
2784 << PointeeTy << Dest->getSourceRange()
2785 << LenExpr->getSourceRange());
2786 break;
2787 }
Nico Webere4a1c642011-06-14 16:14:58 +00002788 }
2789
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002790 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002791 if (isDynamicClassType(PointeeTy)) {
2792
2793 unsigned OperationType = 0;
2794 // "overwritten" if we're warning about the destination for any call
2795 // but memcmp; otherwise a verb appropriate to the call.
2796 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2797 if (BId == Builtin::BImemcpy)
2798 OperationType = 1;
2799 else if(BId == Builtin::BImemmove)
2800 OperationType = 2;
2801 else if (BId == Builtin::BImemcmp)
2802 OperationType = 3;
2803 }
2804
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002805 DiagRuntimeBehavior(
2806 Dest->getExprLoc(), Dest,
2807 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002808 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002809 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002810 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002811 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002812 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2813 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002814 DiagRuntimeBehavior(
2815 Dest->getExprLoc(), Dest,
2816 PDiag(diag::warn_arc_object_memaccess)
2817 << ArgIdx << FnName << PointeeTy
2818 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002819 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002820 continue;
John McCallf85e1932011-06-15 23:02:42 +00002821
2822 DiagRuntimeBehavior(
2823 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002824 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002825 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2826 break;
2827 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002828 }
2829}
2830
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002831// A little helper routine: ignore addition and subtraction of integer literals.
2832// This intentionally does not ignore all integer constant expressions because
2833// we don't want to remove sizeof().
2834static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2835 Ex = Ex->IgnoreParenCasts();
2836
2837 for (;;) {
2838 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2839 if (!BO || !BO->isAdditiveOp())
2840 break;
2841
2842 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2843 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2844
2845 if (isa<IntegerLiteral>(RHS))
2846 Ex = LHS;
2847 else if (isa<IntegerLiteral>(LHS))
2848 Ex = RHS;
2849 else
2850 break;
2851 }
2852
2853 return Ex;
2854}
2855
2856// Warn if the user has made the 'size' argument to strlcpy or strlcat
2857// be the size of the source, instead of the destination.
2858void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2859 IdentifierInfo *FnName) {
2860
2861 // Don't crash if the user has the wrong number of arguments
2862 if (Call->getNumArgs() != 3)
2863 return;
2864
2865 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2866 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2867 const Expr *CompareWithSrc = NULL;
2868
2869 // Look for 'strlcpy(dst, x, sizeof(x))'
2870 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2871 CompareWithSrc = Ex;
2872 else {
2873 // Look for 'strlcpy(dst, x, strlen(x))'
2874 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002875 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002876 && SizeCall->getNumArgs() == 1)
2877 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2878 }
2879 }
2880
2881 if (!CompareWithSrc)
2882 return;
2883
2884 // Determine if the argument to sizeof/strlen is equal to the source
2885 // argument. In principle there's all kinds of things you could do
2886 // here, for instance creating an == expression and evaluating it with
2887 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2888 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2889 if (!SrcArgDRE)
2890 return;
2891
2892 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2893 if (!CompareWithSrcDRE ||
2894 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2895 return;
2896
2897 const Expr *OriginalSizeArg = Call->getArg(2);
2898 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2899 << OriginalSizeArg->getSourceRange() << FnName;
2900
2901 // Output a FIXIT hint if the destination is an array (rather than a
2902 // pointer to an array). This could be enhanced to handle some
2903 // pointers if we know the actual size, like if DstArg is 'array+2'
2904 // we could say 'sizeof(array)-2'.
2905 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002906 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002907
Ted Kremenek8f746222011-08-18 22:48:41 +00002908 // Only handle constant-sized or VLAs, but not flexible members.
2909 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2910 // Only issue the FIXIT for arrays of size > 1.
2911 if (CAT->getSize().getSExtValue() <= 1)
2912 return;
2913 } else if (!DstArgTy->isVariableArrayType()) {
2914 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002915 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002916
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002917 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002918 llvm::raw_svector_ostream OS(sizeString);
2919 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002920 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002921 OS << ")";
2922
2923 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2924 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2925 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002926}
2927
Anna Zaksc36bedc2012-02-01 19:08:57 +00002928/// Check if two expressions refer to the same declaration.
2929static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2930 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2931 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2932 return D1->getDecl() == D2->getDecl();
2933 return false;
2934}
2935
2936static const Expr *getStrlenExprArg(const Expr *E) {
2937 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2938 const FunctionDecl *FD = CE->getDirectCallee();
2939 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2940 return 0;
2941 return CE->getArg(0)->IgnoreParenCasts();
2942 }
2943 return 0;
2944}
2945
2946// Warn on anti-patterns as the 'size' argument to strncat.
2947// The correct size argument should look like following:
2948// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2949void Sema::CheckStrncatArguments(const CallExpr *CE,
2950 IdentifierInfo *FnName) {
2951 // Don't crash if the user has the wrong number of arguments.
2952 if (CE->getNumArgs() < 3)
2953 return;
2954 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2955 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2956 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2957
2958 // Identify common expressions, which are wrongly used as the size argument
2959 // to strncat and may lead to buffer overflows.
2960 unsigned PatternType = 0;
2961 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2962 // - sizeof(dst)
2963 if (referToTheSameDecl(SizeOfArg, DstArg))
2964 PatternType = 1;
2965 // - sizeof(src)
2966 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2967 PatternType = 2;
2968 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2969 if (BE->getOpcode() == BO_Sub) {
2970 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2971 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2972 // - sizeof(dst) - strlen(dst)
2973 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2974 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2975 PatternType = 1;
2976 // - sizeof(src) - (anything)
2977 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2978 PatternType = 2;
2979 }
2980 }
2981
2982 if (PatternType == 0)
2983 return;
2984
Anna Zaksafdb0412012-02-03 01:27:37 +00002985 // Generate the diagnostic.
2986 SourceLocation SL = LenArg->getLocStart();
2987 SourceRange SR = LenArg->getSourceRange();
2988 SourceManager &SM = PP.getSourceManager();
2989
2990 // If the function is defined as a builtin macro, do not show macro expansion.
2991 if (SM.isMacroArgExpansion(SL)) {
2992 SL = SM.getSpellingLoc(SL);
2993 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2994 SM.getSpellingLoc(SR.getEnd()));
2995 }
2996
Anna Zaksc36bedc2012-02-01 19:08:57 +00002997 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002998 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002999 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003000 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003001
3002 // Output a FIXIT hint if the destination is an array (rather than a
3003 // pointer to an array). This could be enhanced to handle some
3004 // pointers if we know the actual size, like if DstArg is 'array+2'
3005 // we could say 'sizeof(array)-2'.
3006 QualType DstArgTy = DstArg->getType();
3007
3008 // Only handle constant-sized or VLAs, but not flexible members.
3009 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
3010 // Only issue the FIXIT for arrays of size > 1.
3011 if (CAT->getSize().getSExtValue() <= 1)
3012 return;
3013 } else if (!DstArgTy->isVariableArrayType()) {
3014 return;
3015 }
3016
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003017 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003018 llvm::raw_svector_ostream OS(sizeString);
3019 OS << "sizeof(";
3020 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3021 OS << ") - ";
3022 OS << "strlen(";
3023 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
3024 OS << ") - 1";
3025
Anna Zaksafdb0412012-02-03 01:27:37 +00003026 Diag(SL, diag::note_strncat_wrong_size)
3027 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003028}
3029
Ted Kremenek06de2762007-08-17 16:46:58 +00003030//===--- CHECK: Return Address of Stack Variable --------------------------===//
3031
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003032static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3033 Decl *ParentDecl);
3034static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3035 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003036
3037/// CheckReturnStackAddr - Check if a return statement returns the address
3038/// of a stack variable.
3039void
3040Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3041 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003043 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003045
3046 // Perform checking for returned stack addresses, local blocks,
3047 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003048 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003049 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003050 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003051 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003052 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003053 }
3054
3055 if (stackE == 0)
3056 return; // Nothing suspicious was found.
3057
3058 SourceLocation diagLoc;
3059 SourceRange diagRange;
3060 if (refVars.empty()) {
3061 diagLoc = stackE->getLocStart();
3062 diagRange = stackE->getSourceRange();
3063 } else {
3064 // We followed through a reference variable. 'stackE' contains the
3065 // problematic expression but we will warn at the return statement pointing
3066 // at the reference variable. We will later display the "trail" of
3067 // reference variables using notes.
3068 diagLoc = refVars[0]->getLocStart();
3069 diagRange = refVars[0]->getSourceRange();
3070 }
3071
3072 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3073 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3074 : diag::warn_ret_stack_addr)
3075 << DR->getDecl()->getDeclName() << diagRange;
3076 } else if (isa<BlockExpr>(stackE)) { // local block.
3077 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3078 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3079 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3080 } else { // local temporary.
3081 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3082 : diag::warn_ret_local_temp_addr)
3083 << diagRange;
3084 }
3085
3086 // Display the "trail" of reference variables that we followed until we
3087 // found the problematic expression using notes.
3088 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3089 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3090 // If this var binds to another reference var, show the range of the next
3091 // var, otherwise the var binds to the problematic expression, in which case
3092 // show the range of the expression.
3093 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3094 : stackE->getSourceRange();
3095 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3096 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003097 }
3098}
3099
3100/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3101/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003102/// to a location on the stack, a local block, an address of a label, or a
3103/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003104/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003105/// encounter a subexpression that (1) clearly does not lead to one of the
3106/// above problematic expressions (2) is something we cannot determine leads to
3107/// a problematic expression based on such local checking.
3108///
3109/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3110/// the expression that they point to. Such variables are added to the
3111/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003112///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003113/// EvalAddr processes expressions that are pointers that are used as
3114/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003115/// At the base case of the recursion is a check for the above problematic
3116/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003117///
3118/// This implementation handles:
3119///
3120/// * pointer-to-pointer casts
3121/// * implicit conversions from array references to pointers
3122/// * taking the address of fields
3123/// * arbitrary interplay between "&" and "*" operators
3124/// * pointer arithmetic from an address of a stack variable
3125/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003126static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3127 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003128 if (E->isTypeDependent())
3129 return NULL;
3130
Ted Kremenek06de2762007-08-17 16:46:58 +00003131 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003132 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003133 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003134 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003135 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Peter Collingbournef111d932011-04-15 00:35:48 +00003137 E = E->IgnoreParens();
3138
Ted Kremenek06de2762007-08-17 16:46:58 +00003139 // Our "symbolic interpreter" is just a dispatch off the currently
3140 // viewed AST node. We then recursively traverse the AST by calling
3141 // EvalAddr and EvalVal appropriately.
3142 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003143 case Stmt::DeclRefExprClass: {
3144 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3145
3146 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3147 // If this is a reference variable, follow through to the expression that
3148 // it points to.
3149 if (V->hasLocalStorage() &&
3150 V->getType()->isReferenceType() && V->hasInit()) {
3151 // Add the reference variable to the "trail".
3152 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003153 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003154 }
3155
3156 return NULL;
3157 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003158
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003159 case Stmt::UnaryOperatorClass: {
3160 // The only unary operator that make sense to handle here
3161 // is AddrOf. All others don't make sense as pointers.
3162 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
John McCall2de56d12010-08-25 11:45:40 +00003164 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003165 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003166 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003167 return NULL;
3168 }
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003170 case Stmt::BinaryOperatorClass: {
3171 // Handle pointer arithmetic. All other binary operators are not valid
3172 // in this context.
3173 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003174 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003175
John McCall2de56d12010-08-25 11:45:40 +00003176 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003177 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003179 Expr *Base = B->getLHS();
3180
3181 // Determine which argument is the real pointer base. It could be
3182 // the RHS argument instead of the LHS.
3183 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003184
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003185 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003186 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003187 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003188
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003189 // For conditional operators we need to see if either the LHS or RHS are
3190 // valid DeclRefExpr*s. If one of them is valid, we return it.
3191 case Stmt::ConditionalOperatorClass: {
3192 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003194 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003195 if (Expr *lhsExpr = C->getLHS()) {
3196 // In C++, we can have a throw-expression, which has 'void' type.
3197 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003198 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003199 return LHS;
3200 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003201
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003202 // In C++, we can have a throw-expression, which has 'void' type.
3203 if (C->getRHS()->getType()->isVoidType())
3204 return NULL;
3205
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003206 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003207 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003208
3209 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003210 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003211 return E; // local block.
3212 return NULL;
3213
3214 case Stmt::AddrLabelExprClass:
3215 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003216
John McCall80ee6e82011-11-10 05:35:25 +00003217 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003218 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3219 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003220
Ted Kremenek54b52742008-08-07 00:49:01 +00003221 // For casts, we need to handle conversions from arrays to
3222 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003223 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003224 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003225 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003226 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003227 case Stmt::CXXStaticCastExprClass:
3228 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003229 case Stmt::CXXConstCastExprClass:
3230 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003231 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3232 switch (cast<CastExpr>(E)->getCastKind()) {
3233 case CK_BitCast:
3234 case CK_LValueToRValue:
3235 case CK_NoOp:
3236 case CK_BaseToDerived:
3237 case CK_DerivedToBase:
3238 case CK_UncheckedDerivedToBase:
3239 case CK_Dynamic:
3240 case CK_CPointerToObjCPointerCast:
3241 case CK_BlockPointerToObjCPointerCast:
3242 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003243 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003244
3245 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003246 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003247
3248 default:
3249 return 0;
3250 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003251 }
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Douglas Gregor03e80032011-06-21 17:03:29 +00003253 case Stmt::MaterializeTemporaryExprClass:
3254 if (Expr *Result = EvalAddr(
3255 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003256 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003257 return Result;
3258
3259 return E;
3260
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003261 // Everything else: we simply don't reason about them.
3262 default:
3263 return NULL;
3264 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003265}
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Ted Kremenek06de2762007-08-17 16:46:58 +00003267
3268/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3269/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003270static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3271 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003272do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003273 // We should only be called for evaluating non-pointer expressions, or
3274 // expressions with a pointer type that are not used as references but instead
3275 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Ted Kremenek06de2762007-08-17 16:46:58 +00003277 // Our "symbolic interpreter" is just a dispatch off the currently
3278 // viewed AST node. We then recursively traverse the AST by calling
3279 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003280
3281 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003282 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003283 case Stmt::ImplicitCastExprClass: {
3284 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003285 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003286 E = IE->getSubExpr();
3287 continue;
3288 }
3289 return NULL;
3290 }
3291
John McCall80ee6e82011-11-10 05:35:25 +00003292 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003293 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003294
Douglas Gregora2813ce2009-10-23 18:54:35 +00003295 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003296 // When we hit a DeclRefExpr we are looking at code that refers to a
3297 // variable's name. If it's not a reference variable we check if it has
3298 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003299 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003301 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3302 // Check if it refers to itself, e.g. "int& i = i;".
3303 if (V == ParentDecl)
3304 return DR;
3305
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003306 if (V->hasLocalStorage()) {
3307 if (!V->getType()->isReferenceType())
3308 return DR;
3309
3310 // Reference variable, follow through to the expression that
3311 // it points to.
3312 if (V->hasInit()) {
3313 // Add the reference variable to the "trail".
3314 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003315 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003316 }
3317 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003318 }
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Ted Kremenek06de2762007-08-17 16:46:58 +00003320 return NULL;
3321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Ted Kremenek06de2762007-08-17 16:46:58 +00003323 case Stmt::UnaryOperatorClass: {
3324 // The only unary operator that make sense to handle here
3325 // is Deref. All others don't resolve to a "name." This includes
3326 // handling all sorts of rvalues passed to a unary operator.
3327 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003328
John McCall2de56d12010-08-25 11:45:40 +00003329 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003330 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003331
3332 return NULL;
3333 }
Mike Stump1eb44332009-09-09 15:08:12 +00003334
Ted Kremenek06de2762007-08-17 16:46:58 +00003335 case Stmt::ArraySubscriptExprClass: {
3336 // Array subscripts are potential references to data on the stack. We
3337 // retrieve the DeclRefExpr* for the array variable if it indeed
3338 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003339 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003340 }
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Ted Kremenek06de2762007-08-17 16:46:58 +00003342 case Stmt::ConditionalOperatorClass: {
3343 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003344 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003345 ConditionalOperator *C = cast<ConditionalOperator>(E);
3346
Anders Carlsson39073232007-11-30 19:04:31 +00003347 // Handle the GNU extension for missing LHS.
3348 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003349 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003350 return LHS;
3351
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003352 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003353 }
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Ted Kremenek06de2762007-08-17 16:46:58 +00003355 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003356 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003357 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003358
Ted Kremenek06de2762007-08-17 16:46:58 +00003359 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003360 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003361 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003362
3363 // Check whether the member type is itself a reference, in which case
3364 // we're not going to refer to the member, but to what the member refers to.
3365 if (M->getMemberDecl()->getType()->isReferenceType())
3366 return NULL;
3367
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003368 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003369 }
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Douglas Gregor03e80032011-06-21 17:03:29 +00003371 case Stmt::MaterializeTemporaryExprClass:
3372 if (Expr *Result = EvalVal(
3373 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003374 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003375 return Result;
3376
3377 return E;
3378
Ted Kremenek06de2762007-08-17 16:46:58 +00003379 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003380 // Check that we don't return or take the address of a reference to a
3381 // temporary. This is only useful in C++.
3382 if (!E->isTypeDependent() && E->isRValue())
3383 return E;
3384
3385 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003386 return NULL;
3387 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003388} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003389}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003390
3391//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3392
3393/// Check for comparisons of floating point operands using != and ==.
3394/// Issue a warning if these are no self-comparisons, as they are not likely
3395/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003396void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003397 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Richard Trieudd225092011-09-15 21:56:47 +00003399 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3400 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003401
3402 // Special case: check for x == x (which is OK).
3403 // Do not emit warnings for such cases.
3404 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3405 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3406 if (DRL->getDecl() == DRR->getDecl())
3407 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
3409
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003410 // Special case: check for comparisons against literals that can be exactly
3411 // represented by APFloat. In such cases, do not emit a warning. This
3412 // is a heuristic: often comparison against such literals are used to
3413 // detect if a value in a variable has not changed. This clearly can
3414 // lead to false negatives.
3415 if (EmitWarning) {
3416 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3417 if (FLL->isExact())
3418 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003419 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003420 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3421 if (FLR->isExact())
3422 EmitWarning = false;
3423 }
3424 }
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003426 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003427 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003428 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003429 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003430 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Sebastian Redl0eb23302009-01-19 00:08:26 +00003432 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003433 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003434 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003435 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003437 // Emit the diagnostic.
3438 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003439 Diag(Loc, diag::warn_floatingpoint_eq)
3440 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003441}
John McCallba26e582010-01-04 23:21:16 +00003442
John McCallf2370c92010-01-06 05:24:50 +00003443//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3444//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003445
John McCallf2370c92010-01-06 05:24:50 +00003446namespace {
John McCallba26e582010-01-04 23:21:16 +00003447
John McCallf2370c92010-01-06 05:24:50 +00003448/// Structure recording the 'active' range of an integer-valued
3449/// expression.
3450struct IntRange {
3451 /// The number of bits active in the int.
3452 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003453
John McCallf2370c92010-01-06 05:24:50 +00003454 /// True if the int is known not to have negative values.
3455 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003456
John McCallf2370c92010-01-06 05:24:50 +00003457 IntRange(unsigned Width, bool NonNegative)
3458 : Width(Width), NonNegative(NonNegative)
3459 {}
John McCallba26e582010-01-04 23:21:16 +00003460
John McCall1844a6e2010-11-10 23:38:19 +00003461 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003462 static IntRange forBoolType() {
3463 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003464 }
3465
John McCall1844a6e2010-11-10 23:38:19 +00003466 /// Returns the range of an opaque value of the given integral type.
3467 static IntRange forValueOfType(ASTContext &C, QualType T) {
3468 return forValueOfCanonicalType(C,
3469 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003470 }
3471
John McCall1844a6e2010-11-10 23:38:19 +00003472 /// Returns the range of an opaque value of a canonical integral type.
3473 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003474 assert(T->isCanonicalUnqualified());
3475
3476 if (const VectorType *VT = dyn_cast<VectorType>(T))
3477 T = VT->getElementType().getTypePtr();
3478 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3479 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003480
John McCall091f23f2010-11-09 22:22:12 +00003481 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003482 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3483 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003484 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003485 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3486
John McCall323ed742010-05-06 08:58:33 +00003487 unsigned NumPositive = Enum->getNumPositiveBits();
3488 unsigned NumNegative = Enum->getNumNegativeBits();
3489
3490 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3491 }
John McCallf2370c92010-01-06 05:24:50 +00003492
3493 const BuiltinType *BT = cast<BuiltinType>(T);
3494 assert(BT->isInteger());
3495
3496 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3497 }
3498
John McCall1844a6e2010-11-10 23:38:19 +00003499 /// Returns the "target" range of a canonical integral type, i.e.
3500 /// the range of values expressible in the type.
3501 ///
3502 /// This matches forValueOfCanonicalType except that enums have the
3503 /// full range of their type, not the range of their enumerators.
3504 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3505 assert(T->isCanonicalUnqualified());
3506
3507 if (const VectorType *VT = dyn_cast<VectorType>(T))
3508 T = VT->getElementType().getTypePtr();
3509 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3510 T = CT->getElementType().getTypePtr();
3511 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003512 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003513
3514 const BuiltinType *BT = cast<BuiltinType>(T);
3515 assert(BT->isInteger());
3516
3517 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3518 }
3519
3520 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003521 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003522 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003523 L.NonNegative && R.NonNegative);
3524 }
3525
John McCall1844a6e2010-11-10 23:38:19 +00003526 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003527 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003528 return IntRange(std::min(L.Width, R.Width),
3529 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003530 }
3531};
3532
Ted Kremenek0692a192012-01-31 05:37:37 +00003533static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3534 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003535 if (value.isSigned() && value.isNegative())
3536 return IntRange(value.getMinSignedBits(), false);
3537
3538 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003539 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003540
3541 // isNonNegative() just checks the sign bit without considering
3542 // signedness.
3543 return IntRange(value.getActiveBits(), true);
3544}
3545
Ted Kremenek0692a192012-01-31 05:37:37 +00003546static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3547 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003548 if (result.isInt())
3549 return GetValueRange(C, result.getInt(), MaxWidth);
3550
3551 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003552 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3553 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3554 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3555 R = IntRange::join(R, El);
3556 }
John McCallf2370c92010-01-06 05:24:50 +00003557 return R;
3558 }
3559
3560 if (result.isComplexInt()) {
3561 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3562 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3563 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003564 }
3565
3566 // This can happen with lossless casts to intptr_t of "based" lvalues.
3567 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003568 // FIXME: The only reason we need to pass the type in here is to get
3569 // the sign right on this one case. It would be nice if APValue
3570 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003571 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003572 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003573}
John McCallf2370c92010-01-06 05:24:50 +00003574
3575/// Pseudo-evaluate the given integer expression, estimating the
3576/// range of values it might take.
3577///
3578/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003579static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003580 E = E->IgnoreParens();
3581
3582 // Try a full evaluation first.
3583 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003584 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003585 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003586
3587 // I think we only want to look through implicit casts here; if the
3588 // user has an explicit widening cast, we should treat the value as
3589 // being of the new, wider type.
3590 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003591 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003592 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3593
John McCall1844a6e2010-11-10 23:38:19 +00003594 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003595
John McCall2de56d12010-08-25 11:45:40 +00003596 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003597
John McCallf2370c92010-01-06 05:24:50 +00003598 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003599 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003600 return OutputTypeRange;
3601
3602 IntRange SubRange
3603 = GetExprRange(C, CE->getSubExpr(),
3604 std::min(MaxWidth, OutputTypeRange.Width));
3605
3606 // Bail out if the subexpr's range is as wide as the cast type.
3607 if (SubRange.Width >= OutputTypeRange.Width)
3608 return OutputTypeRange;
3609
3610 // Otherwise, we take the smaller width, and we're non-negative if
3611 // either the output type or the subexpr is.
3612 return IntRange(SubRange.Width,
3613 SubRange.NonNegative || OutputTypeRange.NonNegative);
3614 }
3615
3616 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3617 // If we can fold the condition, just take that operand.
3618 bool CondResult;
3619 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3620 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3621 : CO->getFalseExpr(),
3622 MaxWidth);
3623
3624 // Otherwise, conservatively merge.
3625 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3626 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3627 return IntRange::join(L, R);
3628 }
3629
3630 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3631 switch (BO->getOpcode()) {
3632
3633 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003634 case BO_LAnd:
3635 case BO_LOr:
3636 case BO_LT:
3637 case BO_GT:
3638 case BO_LE:
3639 case BO_GE:
3640 case BO_EQ:
3641 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003642 return IntRange::forBoolType();
3643
John McCall862ff872011-07-13 06:35:24 +00003644 // The type of the assignments is the type of the LHS, so the RHS
3645 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003646 case BO_MulAssign:
3647 case BO_DivAssign:
3648 case BO_RemAssign:
3649 case BO_AddAssign:
3650 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003651 case BO_XorAssign:
3652 case BO_OrAssign:
3653 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003654 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003655
John McCall862ff872011-07-13 06:35:24 +00003656 // Simple assignments just pass through the RHS, which will have
3657 // been coerced to the LHS type.
3658 case BO_Assign:
3659 // TODO: bitfields?
3660 return GetExprRange(C, BO->getRHS(), MaxWidth);
3661
John McCallf2370c92010-01-06 05:24:50 +00003662 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003663 case BO_PtrMemD:
3664 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003665 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003666
John McCall60fad452010-01-06 22:07:33 +00003667 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003668 case BO_And:
3669 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003670 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3671 GetExprRange(C, BO->getRHS(), MaxWidth));
3672
John McCallf2370c92010-01-06 05:24:50 +00003673 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003674 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003675 // ...except that we want to treat '1 << (blah)' as logically
3676 // positive. It's an important idiom.
3677 if (IntegerLiteral *I
3678 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3679 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003680 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003681 return IntRange(R.Width, /*NonNegative*/ true);
3682 }
3683 }
3684 // fallthrough
3685
John McCall2de56d12010-08-25 11:45:40 +00003686 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003687 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003688
John McCall60fad452010-01-06 22:07:33 +00003689 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003690 case BO_Shr:
3691 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003692 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3693
3694 // If the shift amount is a positive constant, drop the width by
3695 // that much.
3696 llvm::APSInt shift;
3697 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3698 shift.isNonNegative()) {
3699 unsigned zext = shift.getZExtValue();
3700 if (zext >= L.Width)
3701 L.Width = (L.NonNegative ? 0 : 1);
3702 else
3703 L.Width -= zext;
3704 }
3705
3706 return L;
3707 }
3708
3709 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003710 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003711 return GetExprRange(C, BO->getRHS(), MaxWidth);
3712
John McCall60fad452010-01-06 22:07:33 +00003713 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003714 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003715 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003716 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003717 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003718
John McCall00fe7612011-07-14 22:39:48 +00003719 // The width of a division result is mostly determined by the size
3720 // of the LHS.
3721 case BO_Div: {
3722 // Don't 'pre-truncate' the operands.
3723 unsigned opWidth = C.getIntWidth(E->getType());
3724 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3725
3726 // If the divisor is constant, use that.
3727 llvm::APSInt divisor;
3728 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3729 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3730 if (log2 >= L.Width)
3731 L.Width = (L.NonNegative ? 0 : 1);
3732 else
3733 L.Width = std::min(L.Width - log2, MaxWidth);
3734 return L;
3735 }
3736
3737 // Otherwise, just use the LHS's width.
3738 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3739 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3740 }
3741
3742 // The result of a remainder can't be larger than the result of
3743 // either side.
3744 case BO_Rem: {
3745 // Don't 'pre-truncate' the operands.
3746 unsigned opWidth = C.getIntWidth(E->getType());
3747 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3748 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3749
3750 IntRange meet = IntRange::meet(L, R);
3751 meet.Width = std::min(meet.Width, MaxWidth);
3752 return meet;
3753 }
3754
3755 // The default behavior is okay for these.
3756 case BO_Mul:
3757 case BO_Add:
3758 case BO_Xor:
3759 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003760 break;
3761 }
3762
John McCall00fe7612011-07-14 22:39:48 +00003763 // The default case is to treat the operation as if it were closed
3764 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003765 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3766 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3767 return IntRange::join(L, R);
3768 }
3769
3770 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3771 switch (UO->getOpcode()) {
3772 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003773 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003774 return IntRange::forBoolType();
3775
3776 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003777 case UO_Deref:
3778 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003779 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003780
3781 default:
3782 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3783 }
3784 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003785
3786 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003787 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003788 }
John McCallf2370c92010-01-06 05:24:50 +00003789
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003790 if (FieldDecl *BitField = E->getBitField())
3791 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003792 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003793
John McCall1844a6e2010-11-10 23:38:19 +00003794 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003795}
John McCall51313c32010-01-04 23:31:57 +00003796
Ted Kremenek0692a192012-01-31 05:37:37 +00003797static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003798 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3799}
3800
John McCall51313c32010-01-04 23:31:57 +00003801/// Checks whether the given value, which currently has the given
3802/// source semantics, has the same value when coerced through the
3803/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003804static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3805 const llvm::fltSemantics &Src,
3806 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003807 llvm::APFloat truncated = value;
3808
3809 bool ignored;
3810 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3811 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3812
3813 return truncated.bitwiseIsEqual(value);
3814}
3815
3816/// Checks whether the given value, which currently has the given
3817/// source semantics, has the same value when coerced through the
3818/// target semantics.
3819///
3820/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003821static bool IsSameFloatAfterCast(const APValue &value,
3822 const llvm::fltSemantics &Src,
3823 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003824 if (value.isFloat())
3825 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3826
3827 if (value.isVector()) {
3828 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3829 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3830 return false;
3831 return true;
3832 }
3833
3834 assert(value.isComplexFloat());
3835 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3836 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3837}
3838
Ted Kremenek0692a192012-01-31 05:37:37 +00003839static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003840
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003841static bool IsZero(Sema &S, Expr *E) {
3842 // Suppress cases where we are comparing against an enum constant.
3843 if (const DeclRefExpr *DR =
3844 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3845 if (isa<EnumConstantDecl>(DR->getDecl()))
3846 return false;
3847
3848 // Suppress cases where the '0' value is expanded from a macro.
3849 if (E->getLocStart().isMacroID())
3850 return false;
3851
John McCall323ed742010-05-06 08:58:33 +00003852 llvm::APSInt Value;
3853 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3854}
3855
John McCall372e1032010-10-06 00:25:24 +00003856static bool HasEnumType(Expr *E) {
3857 // Strip off implicit integral promotions.
3858 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003859 if (ICE->getCastKind() != CK_IntegralCast &&
3860 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003861 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003862 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003863 }
3864
3865 return E->getType()->isEnumeralType();
3866}
3867
Ted Kremenek0692a192012-01-31 05:37:37 +00003868static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003869 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003870 if (E->isValueDependent())
3871 return;
3872
John McCall2de56d12010-08-25 11:45:40 +00003873 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003874 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003875 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003876 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003877 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003878 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003879 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003880 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003881 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003882 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003883 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003884 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003885 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003886 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003887 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003888 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3889 }
3890}
3891
3892/// Analyze the operands of the given comparison. Implements the
3893/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003894static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3896 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003897}
John McCall51313c32010-01-04 23:31:57 +00003898
John McCallba26e582010-01-04 23:21:16 +00003899/// \brief Implements -Wsign-compare.
3900///
Richard Trieudd225092011-09-15 21:56:47 +00003901/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003902static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003903 // The type the comparison is being performed in.
3904 QualType T = E->getLHS()->getType();
3905 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3906 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003907
John McCall323ed742010-05-06 08:58:33 +00003908 // We don't do anything special if this isn't an unsigned integral
3909 // comparison: we're only interested in integral comparisons, and
3910 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003911 //
3912 // We also don't care about value-dependent expressions or expressions
3913 // whose result is a constant.
3914 if (!T->hasUnsignedIntegerRepresentation()
3915 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003916 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003917
Richard Trieudd225092011-09-15 21:56:47 +00003918 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3919 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003920
John McCall323ed742010-05-06 08:58:33 +00003921 // Check to see if one of the (unmodified) operands is of different
3922 // signedness.
3923 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003924 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3925 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003926 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003927 signedOperand = LHS;
3928 unsignedOperand = RHS;
3929 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3930 signedOperand = RHS;
3931 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003932 } else {
John McCall323ed742010-05-06 08:58:33 +00003933 CheckTrivialUnsignedComparison(S, E);
3934 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003935 }
3936
John McCall323ed742010-05-06 08:58:33 +00003937 // Otherwise, calculate the effective range of the signed operand.
3938 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003939
John McCall323ed742010-05-06 08:58:33 +00003940 // Go ahead and analyze implicit conversions in the operands. Note
3941 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003942 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3943 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003944
John McCall323ed742010-05-06 08:58:33 +00003945 // If the signed range is non-negative, -Wsign-compare won't fire,
3946 // but we should still check for comparisons which are always true
3947 // or false.
3948 if (signedRange.NonNegative)
3949 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003950
3951 // For (in)equality comparisons, if the unsigned operand is a
3952 // constant which cannot collide with a overflowed signed operand,
3953 // then reinterpreting the signed operand as unsigned will not
3954 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003955 if (E->isEqualityOp()) {
3956 unsigned comparisonWidth = S.Context.getIntWidth(T);
3957 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003958
John McCall323ed742010-05-06 08:58:33 +00003959 // We should never be unable to prove that the unsigned operand is
3960 // non-negative.
3961 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3962
3963 if (unsignedRange.Width < comparisonWidth)
3964 return;
3965 }
3966
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00003967 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
3968 S.PDiag(diag::warn_mixed_sign_comparison)
3969 << LHS->getType() << RHS->getType()
3970 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00003971}
3972
John McCall15d7d122010-11-11 03:21:53 +00003973/// Analyzes an attempt to assign the given value to a bitfield.
3974///
3975/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003976static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3977 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003978 assert(Bitfield->isBitField());
3979 if (Bitfield->isInvalidDecl())
3980 return false;
3981
John McCall91b60142010-11-11 05:33:51 +00003982 // White-list bool bitfields.
3983 if (Bitfield->getType()->isBooleanType())
3984 return false;
3985
Douglas Gregor46ff3032011-02-04 13:09:01 +00003986 // Ignore value- or type-dependent expressions.
3987 if (Bitfield->getBitWidth()->isValueDependent() ||
3988 Bitfield->getBitWidth()->isTypeDependent() ||
3989 Init->isValueDependent() ||
3990 Init->isTypeDependent())
3991 return false;
3992
John McCall15d7d122010-11-11 03:21:53 +00003993 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3994
Richard Smith80d4b552011-12-28 19:48:30 +00003995 llvm::APSInt Value;
3996 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003997 return false;
3998
John McCall15d7d122010-11-11 03:21:53 +00003999 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004000 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004001
4002 if (OriginalWidth <= FieldWidth)
4003 return false;
4004
Eli Friedman3a643af2012-01-26 23:11:39 +00004005 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004006 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004007 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004008
Eli Friedman3a643af2012-01-26 23:11:39 +00004009 // Check whether the stored value is equal to the original value.
4010 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00004011 if (Value == TruncatedValue)
4012 return false;
4013
Eli Friedman3a643af2012-01-26 23:11:39 +00004014 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004015 // therefore don't strictly fit into a signed bitfield of width 1.
4016 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004017 return false;
4018
John McCall15d7d122010-11-11 03:21:53 +00004019 std::string PrettyValue = Value.toString(10);
4020 std::string PrettyTrunc = TruncatedValue.toString(10);
4021
4022 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4023 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4024 << Init->getSourceRange();
4025
4026 return true;
4027}
4028
John McCallbeb22aa2010-11-09 23:24:47 +00004029/// Analyze the given simple or compound assignment for warning-worthy
4030/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004031static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004032 // Just recurse on the LHS.
4033 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4034
4035 // We want to recurse on the RHS as normal unless we're assigning to
4036 // a bitfield.
4037 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004038 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4039 E->getOperatorLoc())) {
4040 // Recurse, ignoring any implicit conversions on the RHS.
4041 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4042 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004043 }
4044 }
4045
4046 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4047}
4048
John McCall51313c32010-01-04 23:31:57 +00004049/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004050static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004051 SourceLocation CContext, unsigned diag,
4052 bool pruneControlFlow = false) {
4053 if (pruneControlFlow) {
4054 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4055 S.PDiag(diag)
4056 << SourceType << T << E->getSourceRange()
4057 << SourceRange(CContext));
4058 return;
4059 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004060 S.Diag(E->getExprLoc(), diag)
4061 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4062}
4063
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004064/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004065static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004066 SourceLocation CContext, unsigned diag,
4067 bool pruneControlFlow = false) {
4068 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004069}
4070
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004071/// Diagnose an implicit cast from a literal expression. Does not warn when the
4072/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004073void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4074 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004075 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004076 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004077 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004078 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4079 T->hasUnsignedIntegerRepresentation());
4080 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004081 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004082 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004083 return;
4084
David Blaikiebe0ee872012-05-15 16:56:36 +00004085 SmallString<16> PrettySourceValue;
4086 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004087 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004088 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4089 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4090 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004091 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004092
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004093 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004094 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4095 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004096}
4097
John McCall091f23f2010-11-09 22:22:12 +00004098std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4099 if (!Range.Width) return "0";
4100
4101 llvm::APSInt ValueInRange = Value;
4102 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004103 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004104 return ValueInRange.toString(10);
4105}
4106
John McCall323ed742010-05-06 08:58:33 +00004107void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004108 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004109 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004110
John McCall323ed742010-05-06 08:58:33 +00004111 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4112 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4113 if (Source == Target) return;
4114 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004115
Chandler Carruth108f7562011-07-26 05:40:03 +00004116 // If the conversion context location is invalid don't complain. We also
4117 // don't want to emit a warning if the issue occurs from the expansion of
4118 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4119 // delay this check as long as possible. Once we detect we are in that
4120 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004121 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004122 return;
4123
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004124 // Diagnose implicit casts to bool.
4125 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4126 if (isa<StringLiteral>(E))
4127 // Warn on string literal to bool. Checks for string literals in logical
4128 // expressions, for instances, assert(0 && "error here"), is prevented
4129 // by a check in AnalyzeImplicitConversions().
4130 return DiagnoseImpCast(S, E, T, CC,
4131 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004132 if (Source->isFunctionType()) {
4133 // Warn on function to bool. Checks free functions and static member
4134 // functions. Weakly imported functions are excluded from the check,
4135 // since it's common to test their value to check whether the linker
4136 // found a definition for them.
4137 ValueDecl *D = 0;
4138 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4139 D = R->getDecl();
4140 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4141 D = M->getMemberDecl();
4142 }
4143
4144 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004145 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4146 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4147 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004148 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4149 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4150 QualType ReturnType;
4151 UnresolvedSet<4> NonTemplateOverloads;
4152 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4153 if (!ReturnType.isNull()
4154 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4155 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4156 << FixItHint::CreateInsertion(
4157 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004158 return;
4159 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004160 }
4161 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004162 }
John McCall51313c32010-01-04 23:31:57 +00004163
4164 // Strip vector types.
4165 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004166 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004167 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004168 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004169 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004170 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004171
4172 // If the vector cast is cast between two vectors of the same size, it is
4173 // a bitcast, not a conversion.
4174 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4175 return;
John McCall51313c32010-01-04 23:31:57 +00004176
4177 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4178 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4179 }
4180
4181 // Strip complex types.
4182 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004183 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004184 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004185 return;
4186
John McCallb4eb64d2010-10-08 02:01:28 +00004187 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004188 }
John McCall51313c32010-01-04 23:31:57 +00004189
4190 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4191 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4192 }
4193
4194 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4195 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4196
4197 // If the source is floating point...
4198 if (SourceBT && SourceBT->isFloatingPoint()) {
4199 // ...and the target is floating point...
4200 if (TargetBT && TargetBT->isFloatingPoint()) {
4201 // ...then warn if we're dropping FP rank.
4202
4203 // Builtin FP kinds are ordered by increasing FP rank.
4204 if (SourceBT->getKind() > TargetBT->getKind()) {
4205 // Don't warn about float constants that are precisely
4206 // representable in the target type.
4207 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004208 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004209 // Value might be a float, a float vector, or a float complex.
4210 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004211 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4212 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004213 return;
4214 }
4215
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004216 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004217 return;
4218
John McCallb4eb64d2010-10-08 02:01:28 +00004219 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004220 }
4221 return;
4222 }
4223
Ted Kremenekef9ff882011-03-10 20:03:42 +00004224 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004225 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004226 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004227 return;
4228
Chandler Carrutha5b93322011-02-17 11:05:49 +00004229 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004230 // We also want to warn on, e.g., "int i = -1.234"
4231 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4232 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4233 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4234
Chandler Carruthf65076e2011-04-10 08:36:24 +00004235 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4236 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004237 } else {
4238 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4239 }
4240 }
John McCall51313c32010-01-04 23:31:57 +00004241
4242 return;
4243 }
4244
John McCallf2370c92010-01-06 05:24:50 +00004245 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004246 return;
4247
Richard Trieu1838ca52011-05-29 19:59:02 +00004248 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4249 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004250 SourceLocation Loc = E->getSourceRange().getBegin();
4251 if (Loc.isMacroID())
4252 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4253 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
David Blaikie2c0abf42012-04-30 18:27:22 +00004254 << T << clang::SourceRange(CC)
4255 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004256 return;
4257 }
4258
David Blaikiebe0ee872012-05-15 16:56:36 +00004259 // TODO: remove this early return once the false positives for constant->bool
4260 // in templates, macros, etc, are reduced or removed.
4261 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4262 return;
4263
John McCall323ed742010-05-06 08:58:33 +00004264 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004265 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004266
4267 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004268 // If the source is a constant, use a default-on diagnostic.
4269 // TODO: this should happen for bitfield stores, too.
4270 llvm::APSInt Value(32);
4271 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004272 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004273 return;
4274
John McCall091f23f2010-11-09 22:22:12 +00004275 std::string PrettySourceValue = Value.toString(10);
4276 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4277
Ted Kremenek5e745da2011-10-22 02:37:33 +00004278 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4279 S.PDiag(diag::warn_impcast_integer_precision_constant)
4280 << PrettySourceValue << PrettyTargetValue
4281 << E->getType() << T << E->getSourceRange()
4282 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004283 return;
4284 }
4285
Chris Lattnerb792b302011-06-14 04:51:15 +00004286 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004287 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004288 return;
4289
David Blaikie37050842012-04-12 22:40:54 +00004290 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004291 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4292 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004293 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004294 }
4295
4296 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4297 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4298 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004299
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004300 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004301 return;
4302
John McCall323ed742010-05-06 08:58:33 +00004303 unsigned DiagID = diag::warn_impcast_integer_sign;
4304
4305 // Traditionally, gcc has warned about this under -Wsign-compare.
4306 // We also want to warn about it in -Wconversion.
4307 // So if -Wconversion is off, use a completely identical diagnostic
4308 // in the sign-compare group.
4309 // The conditional-checking code will
4310 if (ICContext) {
4311 DiagID = diag::warn_impcast_integer_sign_conditional;
4312 *ICContext = true;
4313 }
4314
John McCallb4eb64d2010-10-08 02:01:28 +00004315 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004316 }
4317
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004318 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004319 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4320 // type, to give us better diagnostics.
4321 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004322 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004323 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4324 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4325 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4326 SourceType = S.Context.getTypeDeclType(Enum);
4327 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4328 }
4329 }
4330
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004331 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4332 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4333 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004334 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004335 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004336 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004337 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004338 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004339 return;
4340
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004341 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004342 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004343 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004344
John McCall51313c32010-01-04 23:31:57 +00004345 return;
4346}
4347
John McCall323ed742010-05-06 08:58:33 +00004348void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4349
4350void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004351 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004352 E = E->IgnoreParenImpCasts();
4353
4354 if (isa<ConditionalOperator>(E))
4355 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4356
John McCallb4eb64d2010-10-08 02:01:28 +00004357 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004358 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004359 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004360 return;
4361}
4362
4363void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004364 SourceLocation CC = E->getQuestionLoc();
4365
4366 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004367
4368 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004369 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4370 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004371
4372 // If -Wconversion would have warned about either of the candidates
4373 // for a signedness conversion to the context type...
4374 if (!Suspicious) return;
4375
4376 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004377 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4378 CC))
John McCall323ed742010-05-06 08:58:33 +00004379 return;
4380
John McCall323ed742010-05-06 08:58:33 +00004381 // ...then check whether it would have warned about either of the
4382 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004383 if (E->getType() == T) return;
4384
4385 Suspicious = false;
4386 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4387 E->getType(), CC, &Suspicious);
4388 if (!Suspicious)
4389 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004390 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004391}
4392
4393/// AnalyzeImplicitConversions - Find and report any interesting
4394/// implicit conversions in the given expression. There are a couple
4395/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004396void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004397 QualType T = OrigE->getType();
4398 Expr *E = OrigE->IgnoreParenImpCasts();
4399
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004400 if (E->isTypeDependent() || E->isValueDependent())
4401 return;
4402
John McCall323ed742010-05-06 08:58:33 +00004403 // For conditional operators, we analyze the arguments as if they
4404 // were being fed directly into the output.
4405 if (isa<ConditionalOperator>(E)) {
4406 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4407 CheckConditionalOperator(S, CO, T);
4408 return;
4409 }
4410
4411 // Go ahead and check any implicit conversions we might have skipped.
4412 // The non-canonical typecheck is just an optimization;
4413 // CheckImplicitConversion will filter out dead implicit conversions.
4414 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004415 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004416
4417 // Now continue drilling into this expression.
4418
4419 // Skip past explicit casts.
4420 if (isa<ExplicitCastExpr>(E)) {
4421 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004422 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004423 }
4424
John McCallbeb22aa2010-11-09 23:24:47 +00004425 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4426 // Do a somewhat different check with comparison operators.
4427 if (BO->isComparisonOp())
4428 return AnalyzeComparison(S, BO);
4429
Eli Friedman0fa06382012-01-26 23:34:06 +00004430 // And with simple assignments.
4431 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004432 return AnalyzeAssignment(S, BO);
4433 }
John McCall323ed742010-05-06 08:58:33 +00004434
4435 // These break the otherwise-useful invariant below. Fortunately,
4436 // we don't really need to recurse into them, because any internal
4437 // expressions should have been analyzed already when they were
4438 // built into statements.
4439 if (isa<StmtExpr>(E)) return;
4440
4441 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004442 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004443
4444 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004445 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004446 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4447 bool IsLogicalOperator = BO && BO->isLogicalOp();
4448 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004449 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004450 if (!ChildExpr)
4451 continue;
4452
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004453 if (IsLogicalOperator &&
4454 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4455 // Ignore checking string literals that are in logical operators.
4456 continue;
4457 AnalyzeImplicitConversions(S, ChildExpr, CC);
4458 }
John McCall323ed742010-05-06 08:58:33 +00004459}
4460
4461} // end anonymous namespace
4462
4463/// Diagnoses "dangerous" implicit conversions within the given
4464/// expression (which is a full expression). Implements -Wconversion
4465/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004466///
4467/// \param CC the "context" location of the implicit conversion, i.e.
4468/// the most location of the syntactic entity requiring the implicit
4469/// conversion
4470void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004471 // Don't diagnose in unevaluated contexts.
4472 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4473 return;
4474
4475 // Don't diagnose for value- or type-dependent expressions.
4476 if (E->isTypeDependent() || E->isValueDependent())
4477 return;
4478
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004479 // Check for array bounds violations in cases where the check isn't triggered
4480 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4481 // ArraySubscriptExpr is on the RHS of a variable initialization.
4482 CheckArrayAccess(E);
4483
John McCallb4eb64d2010-10-08 02:01:28 +00004484 // This is not the right CC for (e.g.) a variable initialization.
4485 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004486}
4487
John McCall15d7d122010-11-11 03:21:53 +00004488void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4489 FieldDecl *BitField,
4490 Expr *Init) {
4491 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4492}
4493
Mike Stumpf8c49212010-01-21 03:59:47 +00004494/// CheckParmsForFunctionDef - Check that the parameters of the given
4495/// function are appropriate for the definition of a function. This
4496/// takes care of any checks that cannot be performed on the
4497/// declaration itself, e.g., that the types of each of the function
4498/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004499bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4500 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004501 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004502 for (; P != PEnd; ++P) {
4503 ParmVarDecl *Param = *P;
4504
Mike Stumpf8c49212010-01-21 03:59:47 +00004505 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4506 // function declarator that is part of a function definition of
4507 // that function shall not have incomplete type.
4508 //
4509 // This is also C++ [dcl.fct]p6.
4510 if (!Param->isInvalidDecl() &&
4511 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004512 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004513 Param->setInvalidDecl();
4514 HasInvalidParm = true;
4515 }
4516
4517 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4518 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004519 if (CheckParameterNames &&
4520 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004521 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004522 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004523 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004524
4525 // C99 6.7.5.3p12:
4526 // If the function declarator is not part of a definition of that
4527 // function, parameters may have incomplete type and may use the [*]
4528 // notation in their sequences of declarator specifiers to specify
4529 // variable length array types.
4530 QualType PType = Param->getOriginalType();
4531 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4532 if (AT->getSizeModifier() == ArrayType::Star) {
4533 // FIXME: This diagnosic should point the the '[*]' if source-location
4534 // information is added for it.
4535 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4536 }
4537 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004538 }
4539
4540 return HasInvalidParm;
4541}
John McCallb7f4ffe2010-08-12 21:44:57 +00004542
4543/// CheckCastAlign - Implements -Wcast-align, which warns when a
4544/// pointer cast increases the alignment requirements.
4545void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4546 // This is actually a lot of work to potentially be doing on every
4547 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004548 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4549 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004550 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004551 return;
4552
4553 // Ignore dependent types.
4554 if (T->isDependentType() || Op->getType()->isDependentType())
4555 return;
4556
4557 // Require that the destination be a pointer type.
4558 const PointerType *DestPtr = T->getAs<PointerType>();
4559 if (!DestPtr) return;
4560
4561 // If the destination has alignment 1, we're done.
4562 QualType DestPointee = DestPtr->getPointeeType();
4563 if (DestPointee->isIncompleteType()) return;
4564 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4565 if (DestAlign.isOne()) return;
4566
4567 // Require that the source be a pointer type.
4568 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4569 if (!SrcPtr) return;
4570 QualType SrcPointee = SrcPtr->getPointeeType();
4571
4572 // Whitelist casts from cv void*. We already implicitly
4573 // whitelisted casts to cv void*, since they have alignment 1.
4574 // Also whitelist casts involving incomplete types, which implicitly
4575 // includes 'void'.
4576 if (SrcPointee->isIncompleteType()) return;
4577
4578 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4579 if (SrcAlign >= DestAlign) return;
4580
4581 Diag(TRange.getBegin(), diag::warn_cast_align)
4582 << Op->getType() << T
4583 << static_cast<unsigned>(SrcAlign.getQuantity())
4584 << static_cast<unsigned>(DestAlign.getQuantity())
4585 << TRange << Op->getSourceRange();
4586}
4587
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004588static const Type* getElementType(const Expr *BaseExpr) {
4589 const Type* EltType = BaseExpr->getType().getTypePtr();
4590 if (EltType->isAnyPointerType())
4591 return EltType->getPointeeType().getTypePtr();
4592 else if (EltType->isArrayType())
4593 return EltType->getBaseElementTypeUnsafe();
4594 return EltType;
4595}
4596
Chandler Carruthc2684342011-08-05 09:10:50 +00004597/// \brief Check whether this array fits the idiom of a size-one tail padded
4598/// array member of a struct.
4599///
4600/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4601/// commonly used to emulate flexible arrays in C89 code.
4602static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4603 const NamedDecl *ND) {
4604 if (Size != 1 || !ND) return false;
4605
4606 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4607 if (!FD) return false;
4608
4609 // Don't consider sizes resulting from macro expansions or template argument
4610 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004611
4612 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004613 while (TInfo) {
4614 TypeLoc TL = TInfo->getTypeLoc();
4615 // Look through typedefs.
4616 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4617 if (TTL) {
4618 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4619 TInfo = TDL->getTypeSourceInfo();
4620 continue;
4621 }
4622 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4623 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004624 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4625 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004626 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004627 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004628
4629 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004630 if (!RD) return false;
4631 if (RD->isUnion()) return false;
4632 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4633 if (!CRD->isStandardLayout()) return false;
4634 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004635
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004636 // See if this is the last field decl in the record.
4637 const Decl *D = FD;
4638 while ((D = D->getNextDeclInContext()))
4639 if (isa<FieldDecl>(D))
4640 return false;
4641 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004642}
4643
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004644void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004645 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004646 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004647 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004648 if (IndexExpr->isValueDependent())
4649 return;
4650
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004651 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004652 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004653 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004654 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004655 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004656 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004657
Chandler Carruth34064582011-02-17 20:55:08 +00004658 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004659 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004660 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004661 if (IndexNegated)
4662 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004663
Chandler Carruthba447122011-08-05 08:07:29 +00004664 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004665 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4666 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004667 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004668 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004669
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004670 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004671 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004672 if (!size.isStrictlyPositive())
4673 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004674
4675 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004676 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004677 // Make sure we're comparing apples to apples when comparing index to size
4678 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4679 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004680 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004681 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004682 if (ptrarith_typesize != array_typesize) {
4683 // There's a cast to a different size type involved
4684 uint64_t ratio = array_typesize / ptrarith_typesize;
4685 // TODO: Be smarter about handling cases where array_typesize is not a
4686 // multiple of ptrarith_typesize
4687 if (ptrarith_typesize * ratio == array_typesize)
4688 size *= llvm::APInt(size.getBitWidth(), ratio);
4689 }
4690 }
4691
Chandler Carruth34064582011-02-17 20:55:08 +00004692 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004693 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004694 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004695 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004696
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004697 // For array subscripting the index must be less than size, but for pointer
4698 // arithmetic also allow the index (offset) to be equal to size since
4699 // computing the next address after the end of the array is legal and
4700 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004701 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004702 return;
4703
4704 // Also don't warn for arrays of size 1 which are members of some
4705 // structure. These are often used to approximate flexible arrays in C89
4706 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004707 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004708 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004709
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004710 // Suppress the warning if the subscript expression (as identified by the
4711 // ']' location) and the index expression are both from macro expansions
4712 // within a system header.
4713 if (ASE) {
4714 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4715 ASE->getRBracketLoc());
4716 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4717 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4718 IndexExpr->getLocStart());
4719 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4720 return;
4721 }
4722 }
4723
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004724 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004725 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004726 DiagID = diag::warn_array_index_exceeds_bounds;
4727
4728 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4729 PDiag(DiagID) << index.toString(10, true)
4730 << size.toString(10, true)
4731 << (unsigned)size.getLimitedValue(~0U)
4732 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004733 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004734 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004735 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004736 DiagID = diag::warn_ptr_arith_precedes_bounds;
4737 if (index.isNegative()) index = -index;
4738 }
4739
4740 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4741 PDiag(DiagID) << index.toString(10, true)
4742 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004743 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004744
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004745 if (!ND) {
4746 // Try harder to find a NamedDecl to point at in the note.
4747 while (const ArraySubscriptExpr *ASE =
4748 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4749 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4750 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4751 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4752 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4753 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4754 }
4755
Chandler Carruth35001ca2011-02-17 21:10:52 +00004756 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004757 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4758 PDiag(diag::note_array_index_out_of_bounds)
4759 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004760}
4761
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004762void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004763 int AllowOnePastEnd = 0;
4764 while (expr) {
4765 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004766 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004767 case Stmt::ArraySubscriptExprClass: {
4768 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004769 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004770 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004771 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004772 }
4773 case Stmt::UnaryOperatorClass: {
4774 // Only unwrap the * and & unary operators
4775 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4776 expr = UO->getSubExpr();
4777 switch (UO->getOpcode()) {
4778 case UO_AddrOf:
4779 AllowOnePastEnd++;
4780 break;
4781 case UO_Deref:
4782 AllowOnePastEnd--;
4783 break;
4784 default:
4785 return;
4786 }
4787 break;
4788 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004789 case Stmt::ConditionalOperatorClass: {
4790 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4791 if (const Expr *lhs = cond->getLHS())
4792 CheckArrayAccess(lhs);
4793 if (const Expr *rhs = cond->getRHS())
4794 CheckArrayAccess(rhs);
4795 return;
4796 }
4797 default:
4798 return;
4799 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004800 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004801}
John McCallf85e1932011-06-15 23:02:42 +00004802
4803//===--- CHECK: Objective-C retain cycles ----------------------------------//
4804
4805namespace {
4806 struct RetainCycleOwner {
4807 RetainCycleOwner() : Variable(0), Indirect(false) {}
4808 VarDecl *Variable;
4809 SourceRange Range;
4810 SourceLocation Loc;
4811 bool Indirect;
4812
4813 void setLocsFrom(Expr *e) {
4814 Loc = e->getExprLoc();
4815 Range = e->getSourceRange();
4816 }
4817 };
4818}
4819
4820/// Consider whether capturing the given variable can possibly lead to
4821/// a retain cycle.
4822static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4823 // In ARC, it's captured strongly iff the variable has __strong
4824 // lifetime. In MRR, it's captured strongly if the variable is
4825 // __block and has an appropriate type.
4826 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4827 return false;
4828
4829 owner.Variable = var;
4830 owner.setLocsFrom(ref);
4831 return true;
4832}
4833
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004834static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004835 while (true) {
4836 e = e->IgnoreParens();
4837 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4838 switch (cast->getCastKind()) {
4839 case CK_BitCast:
4840 case CK_LValueBitCast:
4841 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004842 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004843 e = cast->getSubExpr();
4844 continue;
4845
John McCallf85e1932011-06-15 23:02:42 +00004846 default:
4847 return false;
4848 }
4849 }
4850
4851 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4852 ObjCIvarDecl *ivar = ref->getDecl();
4853 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4854 return false;
4855
4856 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004857 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004858 return false;
4859
4860 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4861 owner.Indirect = true;
4862 return true;
4863 }
4864
4865 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4866 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4867 if (!var) return false;
4868 return considerVariable(var, ref, owner);
4869 }
4870
John McCallf85e1932011-06-15 23:02:42 +00004871 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4872 if (member->isArrow()) return false;
4873
4874 // Don't count this as an indirect ownership.
4875 e = member->getBase();
4876 continue;
4877 }
4878
John McCall4b9c2d22011-11-06 09:01:30 +00004879 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4880 // Only pay attention to pseudo-objects on property references.
4881 ObjCPropertyRefExpr *pre
4882 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4883 ->IgnoreParens());
4884 if (!pre) return false;
4885 if (pre->isImplicitProperty()) return false;
4886 ObjCPropertyDecl *property = pre->getExplicitProperty();
4887 if (!property->isRetaining() &&
4888 !(property->getPropertyIvarDecl() &&
4889 property->getPropertyIvarDecl()->getType()
4890 .getObjCLifetime() == Qualifiers::OCL_Strong))
4891 return false;
4892
4893 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004894 if (pre->isSuperReceiver()) {
4895 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4896 if (!owner.Variable)
4897 return false;
4898 owner.Loc = pre->getLocation();
4899 owner.Range = pre->getSourceRange();
4900 return true;
4901 }
John McCall4b9c2d22011-11-06 09:01:30 +00004902 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4903 ->getSourceExpr());
4904 continue;
4905 }
4906
John McCallf85e1932011-06-15 23:02:42 +00004907 // Array ivars?
4908
4909 return false;
4910 }
4911}
4912
4913namespace {
4914 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4915 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4916 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4917 Variable(variable), Capturer(0) {}
4918
4919 VarDecl *Variable;
4920 Expr *Capturer;
4921
4922 void VisitDeclRefExpr(DeclRefExpr *ref) {
4923 if (ref->getDecl() == Variable && !Capturer)
4924 Capturer = ref;
4925 }
4926
John McCallf85e1932011-06-15 23:02:42 +00004927 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4928 if (Capturer) return;
4929 Visit(ref->getBase());
4930 if (Capturer && ref->isFreeIvar())
4931 Capturer = ref;
4932 }
4933
4934 void VisitBlockExpr(BlockExpr *block) {
4935 // Look inside nested blocks
4936 if (block->getBlockDecl()->capturesVariable(Variable))
4937 Visit(block->getBlockDecl()->getBody());
4938 }
4939 };
4940}
4941
4942/// Check whether the given argument is a block which captures a
4943/// variable.
4944static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4945 assert(owner.Variable && owner.Loc.isValid());
4946
4947 e = e->IgnoreParenCasts();
4948 BlockExpr *block = dyn_cast<BlockExpr>(e);
4949 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4950 return 0;
4951
4952 FindCaptureVisitor visitor(S.Context, owner.Variable);
4953 visitor.Visit(block->getBlockDecl()->getBody());
4954 return visitor.Capturer;
4955}
4956
4957static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4958 RetainCycleOwner &owner) {
4959 assert(capturer);
4960 assert(owner.Variable && owner.Loc.isValid());
4961
4962 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4963 << owner.Variable << capturer->getSourceRange();
4964 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4965 << owner.Indirect << owner.Range;
4966}
4967
4968/// Check for a keyword selector that starts with the word 'add' or
4969/// 'set'.
4970static bool isSetterLikeSelector(Selector sel) {
4971 if (sel.isUnarySelector()) return false;
4972
Chris Lattner5f9e2722011-07-23 10:55:15 +00004973 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004974 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004975 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004976 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004977 else if (str.startswith("add")) {
4978 // Specially whitelist 'addOperationWithBlock:'.
4979 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4980 return false;
4981 str = str.substr(3);
4982 }
John McCallf85e1932011-06-15 23:02:42 +00004983 else
4984 return false;
4985
4986 if (str.empty()) return true;
4987 return !islower(str.front());
4988}
4989
4990/// Check a message send to see if it's likely to cause a retain cycle.
4991void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4992 // Only check instance methods whose selector looks like a setter.
4993 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4994 return;
4995
4996 // Try to find a variable that the receiver is strongly owned by.
4997 RetainCycleOwner owner;
4998 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004999 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005000 return;
5001 } else {
5002 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5003 owner.Variable = getCurMethodDecl()->getSelfDecl();
5004 owner.Loc = msg->getSuperLoc();
5005 owner.Range = msg->getSuperLoc();
5006 }
5007
5008 // Check whether the receiver is captured by any of the arguments.
5009 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5010 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5011 return diagnoseRetainCycle(*this, capturer, owner);
5012}
5013
5014/// Check a property assign to see if it's likely to cause a retain cycle.
5015void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5016 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005017 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005018 return;
5019
5020 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5021 diagnoseRetainCycle(*this, capturer, owner);
5022}
5023
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005024bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005025 QualType LHS, Expr *RHS) {
5026 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5027 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005028 return false;
5029 // strip off any implicit cast added to get to the one arc-specific
5030 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005031 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005032 Diag(Loc, diag::warn_arc_retained_assign)
5033 << (LT == Qualifiers::OCL_ExplicitNone)
5034 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005035 return true;
5036 }
5037 RHS = cast->getSubExpr();
5038 }
5039 return false;
John McCallf85e1932011-06-15 23:02:42 +00005040}
5041
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005042void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5043 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005044 QualType LHSType;
5045 // PropertyRef on LHS type need be directly obtained from
5046 // its declaration as it has a PsuedoType.
5047 ObjCPropertyRefExpr *PRE
5048 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5049 if (PRE && !PRE->isImplicitProperty()) {
5050 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5051 if (PD)
5052 LHSType = PD->getType();
5053 }
5054
5055 if (LHSType.isNull())
5056 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005057 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5058 return;
5059 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5060 // FIXME. Check for other life times.
5061 if (LT != Qualifiers::OCL_None)
5062 return;
5063
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005064 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005065 if (PRE->isImplicitProperty())
5066 return;
5067 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5068 if (!PD)
5069 return;
5070
5071 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005072 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5073 // when 'assign' attribute was not explicitly specified
5074 // by user, ignore it and rely on property type itself
5075 // for lifetime info.
5076 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5077 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5078 LHSType->isObjCRetainableType())
5079 return;
5080
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005081 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005082 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005083 Diag(Loc, diag::warn_arc_retained_property_assign)
5084 << RHS->getSourceRange();
5085 return;
5086 }
5087 RHS = cast->getSubExpr();
5088 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005089 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005090 }
5091}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005092
5093//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5094
5095namespace {
5096bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5097 SourceLocation StmtLoc,
5098 const NullStmt *Body) {
5099 // Do not warn if the body is a macro that expands to nothing, e.g:
5100 //
5101 // #define CALL(x)
5102 // if (condition)
5103 // CALL(0);
5104 //
5105 if (Body->hasLeadingEmptyMacro())
5106 return false;
5107
5108 // Get line numbers of statement and body.
5109 bool StmtLineInvalid;
5110 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5111 &StmtLineInvalid);
5112 if (StmtLineInvalid)
5113 return false;
5114
5115 bool BodyLineInvalid;
5116 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5117 &BodyLineInvalid);
5118 if (BodyLineInvalid)
5119 return false;
5120
5121 // Warn if null statement and body are on the same line.
5122 if (StmtLine != BodyLine)
5123 return false;
5124
5125 return true;
5126}
5127} // Unnamed namespace
5128
5129void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5130 const Stmt *Body,
5131 unsigned DiagID) {
5132 // Since this is a syntactic check, don't emit diagnostic for template
5133 // instantiations, this just adds noise.
5134 if (CurrentInstantiationScope)
5135 return;
5136
5137 // The body should be a null statement.
5138 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5139 if (!NBody)
5140 return;
5141
5142 // Do the usual checks.
5143 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5144 return;
5145
5146 Diag(NBody->getSemiLoc(), DiagID);
5147 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5148}
5149
5150void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5151 const Stmt *PossibleBody) {
5152 assert(!CurrentInstantiationScope); // Ensured by caller
5153
5154 SourceLocation StmtLoc;
5155 const Stmt *Body;
5156 unsigned DiagID;
5157 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5158 StmtLoc = FS->getRParenLoc();
5159 Body = FS->getBody();
5160 DiagID = diag::warn_empty_for_body;
5161 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5162 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5163 Body = WS->getBody();
5164 DiagID = diag::warn_empty_while_body;
5165 } else
5166 return; // Neither `for' nor `while'.
5167
5168 // The body should be a null statement.
5169 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5170 if (!NBody)
5171 return;
5172
5173 // Skip expensive checks if diagnostic is disabled.
5174 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5175 DiagnosticsEngine::Ignored)
5176 return;
5177
5178 // Do the usual checks.
5179 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5180 return;
5181
5182 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5183 // noise level low, emit diagnostics only if for/while is followed by a
5184 // CompoundStmt, e.g.:
5185 // for (int i = 0; i < n; i++);
5186 // {
5187 // a(i);
5188 // }
5189 // or if for/while is followed by a statement with more indentation
5190 // than for/while itself:
5191 // for (int i = 0; i < n; i++);
5192 // a(i);
5193 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5194 if (!ProbableTypo) {
5195 bool BodyColInvalid;
5196 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5197 PossibleBody->getLocStart(),
5198 &BodyColInvalid);
5199 if (BodyColInvalid)
5200 return;
5201
5202 bool StmtColInvalid;
5203 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5204 S->getLocStart(),
5205 &StmtColInvalid);
5206 if (StmtColInvalid)
5207 return;
5208
5209 if (BodyCol > StmtCol)
5210 ProbableTypo = true;
5211 }
5212
5213 if (ProbableTypo) {
5214 Diag(NBody->getSemiLoc(), DiagID);
5215 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5216 }
5217}