blob: e85024fc5565e0138d01f7a57e8b1cd26a873d5e [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000269 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000302 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000358 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000445 };
446
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
450 return false;
451
452 // Check that the immediate argument is actually a constant.
453 llvm::APSInt Result;
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
455 return true;
456
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
462
463 return false;
464}
465
Richard Smith831421f2012-06-25 20:30:08 +0000466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467/// parameter with the FormatAttr's correct format_idx and firstDataArg.
468/// Returns true when the format fits the function and the FormatStringInfo has
469/// been populated.
470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000475
Richard Smith831421f2012-06-25 20:30:08 +0000476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
479 if (IsCXXMember) {
480 if(FSI->FormatIdx == 0)
481 return false;
482 --FSI->FormatIdx;
483 if (FSI->FirstDataArg != 0)
484 --FSI->FirstDataArg;
485 }
486 return true;
487}
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Richard Smith831421f2012-06-25 20:30:08 +0000489/// Handles the checks for format strings, non-POD arguments to vararg
490/// functions, and NULL arguments passed to non-NULL parameters.
491void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
492 unsigned NumArgs,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
495 SourceLocation Loc,
496 SourceRange Range,
497 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000498 // FIXME: This mechanism should be abstracted to be less fragile and
499 // more efficient. For example, just map function ids to custom
500 // handlers.
501
Ted Kremenekc82faca2010-09-09 04:33:05 +0000502 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000503 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000504 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000505 I = FDecl->specific_attr_begin<FormatAttr>(),
506 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000507 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
508 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000509 HandledFormatString = true;
510
511 // Refuse POD arguments that weren't caught by the format string
512 // checks above.
513 if (!HandledFormatString && CallType != VariadicDoesNotApply)
514 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
515 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenekc82faca2010-09-09 04:33:05 +0000517 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000518 I = FDecl->specific_attr_begin<NonNullAttr>(),
519 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
520 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000521
522 // Type safety checking.
523 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
524 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
525 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
526 CheckArgumentWithTypeTag(*i, Args);
527 }
Richard Smith831421f2012-06-25 20:30:08 +0000528}
529
530/// CheckConstructorCall - Check a constructor call for correctness and safety
531/// properties not enforced by the C type system.
532void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
533 unsigned NumArgs,
534 const FunctionProtoType *Proto,
535 SourceLocation Loc) {
536 VariadicCallType CallType =
537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
538 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
539 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
540}
541
542/// CheckFunctionCall - Check a direct function call for various correctness
543/// and safety properties not strictly enforced by the C type system.
544bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
545 const FunctionProtoType *Proto) {
546 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
547 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
548 TheCall->getCallee());
549 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
550 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
551 IsMemberFunction, TheCall->getRParenLoc(),
552 TheCall->getCallee()->getSourceRange(), CallType);
553
554 IdentifierInfo *FnInfo = FDecl->getIdentifier();
555 // None of the checks below are needed for functions that don't have
556 // simple names (e.g., C++ conversion functions).
557 if (!FnInfo)
558 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000559
Anna Zaks0a151a12012-01-17 00:37:07 +0000560 unsigned CMId = FDecl->getMemoryFunctionKind();
561 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000562 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000563
Anna Zaksd9b859a2012-01-13 21:52:01 +0000564 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000565 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000566 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000567 else if (CMId == Builtin::BIstrncat)
568 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000569 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000570 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000571
Anders Carlssond406bf02009-08-16 01:56:34 +0000572 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000573}
574
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000575bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
576 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000577 VariadicCallType CallType =
578 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000579
Richard Smith831421f2012-06-25 20:30:08 +0000580 checkCall(Method, Args, NumArgs, Method->param_size(),
581 /*IsMemberFunction=*/false,
582 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000583
584 return false;
585}
586
Richard Smith831421f2012-06-25 20:30:08 +0000587bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
588 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000589 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
590 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000591 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000593 QualType Ty = V->getType();
594 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000595 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Richard Smith831421f2012-06-25 20:30:08 +0000597 VariadicCallType CallType =
598 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
599 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000600
Richard Smith831421f2012-06-25 20:30:08 +0000601 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
602 NumProtoArgs, /*IsMemberFunction=*/false,
603 TheCall->getRParenLoc(),
604 TheCall->getCallee()->getSourceRange(), CallType);
605
Anders Carlssond406bf02009-08-16 01:56:34 +0000606 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607}
608
Richard Smithff34d402012-04-12 05:08:17 +0000609ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
610 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000611 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
612 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000613
Richard Smithff34d402012-04-12 05:08:17 +0000614 // All these operations take one of the following forms:
615 enum {
616 // C __c11_atomic_init(A *, C)
617 Init,
618 // C __c11_atomic_load(A *, int)
619 Load,
620 // void __atomic_load(A *, CP, int)
621 Copy,
622 // C __c11_atomic_add(A *, M, int)
623 Arithmetic,
624 // C __atomic_exchange_n(A *, CP, int)
625 Xchg,
626 // void __atomic_exchange(A *, C *, CP, int)
627 GNUXchg,
628 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
629 C11CmpXchg,
630 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
631 GNUCmpXchg
632 } Form = Init;
633 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
634 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
635 // where:
636 // C is an appropriate type,
637 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
638 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
639 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
640 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000641
Richard Smithff34d402012-04-12 05:08:17 +0000642 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
643 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
644 && "need to update code for modified C11 atomics");
645 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
646 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
647 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
648 Op == AtomicExpr::AO__atomic_store_n ||
649 Op == AtomicExpr::AO__atomic_exchange_n ||
650 Op == AtomicExpr::AO__atomic_compare_exchange_n;
651 bool IsAddSub = false;
652
653 switch (Op) {
654 case AtomicExpr::AO__c11_atomic_init:
655 Form = Init;
656 break;
657
658 case AtomicExpr::AO__c11_atomic_load:
659 case AtomicExpr::AO__atomic_load_n:
660 Form = Load;
661 break;
662
663 case AtomicExpr::AO__c11_atomic_store:
664 case AtomicExpr::AO__atomic_load:
665 case AtomicExpr::AO__atomic_store:
666 case AtomicExpr::AO__atomic_store_n:
667 Form = Copy;
668 break;
669
670 case AtomicExpr::AO__c11_atomic_fetch_add:
671 case AtomicExpr::AO__c11_atomic_fetch_sub:
672 case AtomicExpr::AO__atomic_fetch_add:
673 case AtomicExpr::AO__atomic_fetch_sub:
674 case AtomicExpr::AO__atomic_add_fetch:
675 case AtomicExpr::AO__atomic_sub_fetch:
676 IsAddSub = true;
677 // Fall through.
678 case AtomicExpr::AO__c11_atomic_fetch_and:
679 case AtomicExpr::AO__c11_atomic_fetch_or:
680 case AtomicExpr::AO__c11_atomic_fetch_xor:
681 case AtomicExpr::AO__atomic_fetch_and:
682 case AtomicExpr::AO__atomic_fetch_or:
683 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000684 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000685 case AtomicExpr::AO__atomic_and_fetch:
686 case AtomicExpr::AO__atomic_or_fetch:
687 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000688 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000689 Form = Arithmetic;
690 break;
691
692 case AtomicExpr::AO__c11_atomic_exchange:
693 case AtomicExpr::AO__atomic_exchange_n:
694 Form = Xchg;
695 break;
696
697 case AtomicExpr::AO__atomic_exchange:
698 Form = GNUXchg;
699 break;
700
701 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
702 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
703 Form = C11CmpXchg;
704 break;
705
706 case AtomicExpr::AO__atomic_compare_exchange:
707 case AtomicExpr::AO__atomic_compare_exchange_n:
708 Form = GNUCmpXchg;
709 break;
710 }
711
712 // Check we have the right number of arguments.
713 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000714 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000715 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000716 << TheCall->getCallee()->getSourceRange();
717 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000718 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
719 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000720 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000721 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000722 << TheCall->getCallee()->getSourceRange();
723 return ExprError();
724 }
725
Richard Smithff34d402012-04-12 05:08:17 +0000726 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000727 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000728 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
729 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
730 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000731 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000732 << Ptr->getType() << Ptr->getSourceRange();
733 return ExprError();
734 }
735
Richard Smithff34d402012-04-12 05:08:17 +0000736 // For a __c11 builtin, this should be a pointer to an _Atomic type.
737 QualType AtomTy = pointerType->getPointeeType(); // 'A'
738 QualType ValType = AtomTy; // 'C'
739 if (IsC11) {
740 if (!AtomTy->isAtomicType()) {
741 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
742 << Ptr->getType() << Ptr->getSourceRange();
743 return ExprError();
744 }
Richard Smithbc57b102012-09-15 06:09:58 +0000745 if (AtomTy.isConstQualified()) {
746 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
747 << Ptr->getType() << Ptr->getSourceRange();
748 return ExprError();
749 }
Richard Smithff34d402012-04-12 05:08:17 +0000750 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000751 }
Eli Friedman276b0612011-10-11 02:20:01 +0000752
Richard Smithff34d402012-04-12 05:08:17 +0000753 // For an arithmetic operation, the implied arithmetic must be well-formed.
754 if (Form == Arithmetic) {
755 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
756 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
757 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
758 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
759 return ExprError();
760 }
761 if (!IsAddSub && !ValType->isIntegerType()) {
762 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
763 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
764 return ExprError();
765 }
766 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
767 // For __atomic_*_n operations, the value type must be a scalar integral or
768 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000770 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
771 return ExprError();
772 }
773
774 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
775 // For GNU atomics, require a trivially-copyable type. This is not part of
776 // the GNU atomics specification, but we enforce it for sanity.
777 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000778 << Ptr->getType() << Ptr->getSourceRange();
779 return ExprError();
780 }
781
Richard Smithff34d402012-04-12 05:08:17 +0000782 // FIXME: For any builtin other than a load, the ValType must not be
783 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000784
785 switch (ValType.getObjCLifetime()) {
786 case Qualifiers::OCL_None:
787 case Qualifiers::OCL_ExplicitNone:
788 // okay
789 break;
790
791 case Qualifiers::OCL_Weak:
792 case Qualifiers::OCL_Strong:
793 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000794 // FIXME: Can this happen? By this point, ValType should be known
795 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000796 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
797 << ValType << Ptr->getSourceRange();
798 return ExprError();
799 }
800
801 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000802 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000803 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000804 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000805 ResultType = Context.BoolTy;
806
Richard Smithff34d402012-04-12 05:08:17 +0000807 // The type of a parameter passed 'by value'. In the GNU atomics, such
808 // arguments are actually passed as pointers.
809 QualType ByValType = ValType; // 'CP'
810 if (!IsC11 && !IsN)
811 ByValType = Ptr->getType();
812
Eli Friedman276b0612011-10-11 02:20:01 +0000813 // The first argument --- the pointer --- has a fixed type; we
814 // deduce the types of the rest of the arguments accordingly. Walk
815 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000816 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000817 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000818 if (i < NumVals[Form] + 1) {
819 switch (i) {
820 case 1:
821 // The second argument is the non-atomic operand. For arithmetic, this
822 // is always passed by value, and for a compare_exchange it is always
823 // passed by address. For the rest, GNU uses by-address and C11 uses
824 // by-value.
825 assert(Form != Load);
826 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
827 Ty = ValType;
828 else if (Form == Copy || Form == Xchg)
829 Ty = ByValType;
830 else if (Form == Arithmetic)
831 Ty = Context.getPointerDiffType();
832 else
833 Ty = Context.getPointerType(ValType.getUnqualifiedType());
834 break;
835 case 2:
836 // The third argument to compare_exchange / GNU exchange is a
837 // (pointer to a) desired value.
838 Ty = ByValType;
839 break;
840 case 3:
841 // The fourth argument to GNU compare_exchange is a 'weak' flag.
842 Ty = Context.BoolTy;
843 break;
844 }
Eli Friedman276b0612011-10-11 02:20:01 +0000845 } else {
846 // The order(s) are always converted to int.
847 Ty = Context.IntTy;
848 }
Richard Smithff34d402012-04-12 05:08:17 +0000849
Eli Friedman276b0612011-10-11 02:20:01 +0000850 InitializedEntity Entity =
851 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000852 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000853 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
854 if (Arg.isInvalid())
855 return true;
856 TheCall->setArg(i, Arg.get());
857 }
858
Richard Smithff34d402012-04-12 05:08:17 +0000859 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000860 SmallVector<Expr*, 5> SubExprs;
861 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000862 switch (Form) {
863 case Init:
864 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000865 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000866 break;
867 case Load:
868 SubExprs.push_back(TheCall->getArg(1)); // Order
869 break;
870 case Copy:
871 case Arithmetic:
872 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000873 SubExprs.push_back(TheCall->getArg(2)); // Order
874 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000875 break;
876 case GNUXchg:
877 // Note, AtomicExpr::getVal2() has a special case for this atomic.
878 SubExprs.push_back(TheCall->getArg(3)); // Order
879 SubExprs.push_back(TheCall->getArg(1)); // Val1
880 SubExprs.push_back(TheCall->getArg(2)); // Val2
881 break;
882 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000883 SubExprs.push_back(TheCall->getArg(3)); // Order
884 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000885 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000886 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000887 break;
888 case GNUCmpXchg:
889 SubExprs.push_back(TheCall->getArg(4)); // Order
890 SubExprs.push_back(TheCall->getArg(1)); // Val1
891 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
892 SubExprs.push_back(TheCall->getArg(2)); // Val2
893 SubExprs.push_back(TheCall->getArg(3)); // Weak
894 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000895 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000896
897 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000898 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000899 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000900}
901
902
John McCall5f8d6042011-08-27 01:09:30 +0000903/// checkBuiltinArgument - Given a call to a builtin function, perform
904/// normal type-checking on the given argument, updating the call in
905/// place. This is useful when a builtin function requires custom
906/// type-checking for some of its arguments but not necessarily all of
907/// them.
908///
909/// Returns true on error.
910static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
911 FunctionDecl *Fn = E->getDirectCallee();
912 assert(Fn && "builtin call without direct callee!");
913
914 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
915 InitializedEntity Entity =
916 InitializedEntity::InitializeParameter(S.Context, Param);
917
918 ExprResult Arg = E->getArg(0);
919 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
920 if (Arg.isInvalid())
921 return true;
922
923 E->setArg(ArgIndex, Arg.take());
924 return false;
925}
926
Chris Lattner5caa3702009-05-08 06:58:22 +0000927/// SemaBuiltinAtomicOverloaded - We have a call to a function like
928/// __sync_fetch_and_add, which is an overloaded function based on the pointer
929/// type of its first argument. The main ActOnCallExpr routines have already
930/// promoted the types of arguments because all of these calls are prototyped as
931/// void(...).
932///
933/// This function goes through and does final semantic checking for these
934/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000935ExprResult
936Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000937 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000938 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
939 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
940
941 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000942 if (TheCall->getNumArgs() < 1) {
943 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
944 << 0 << 1 << TheCall->getNumArgs()
945 << TheCall->getCallee()->getSourceRange();
946 return ExprError();
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner5caa3702009-05-08 06:58:22 +0000949 // Inspect the first argument of the atomic builtin. This should always be
950 // a pointer type, whose element is an integral scalar or pointer type.
951 // Because it is a pointer type, we don't have to worry about any implicit
952 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000953 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000954 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000955 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
956 if (FirstArgResult.isInvalid())
957 return ExprError();
958 FirstArg = FirstArgResult.take();
959 TheCall->setArg(0, FirstArg);
960
John McCallf85e1932011-06-15 23:02:42 +0000961 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
962 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000963 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
964 << FirstArg->getType() << FirstArg->getSourceRange();
965 return ExprError();
966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
John McCallf85e1932011-06-15 23:02:42 +0000968 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000969 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000970 !ValType->isBlockPointerType()) {
971 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
972 << FirstArg->getType() << FirstArg->getSourceRange();
973 return ExprError();
974 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000975
John McCallf85e1932011-06-15 23:02:42 +0000976 switch (ValType.getObjCLifetime()) {
977 case Qualifiers::OCL_None:
978 case Qualifiers::OCL_ExplicitNone:
979 // okay
980 break;
981
982 case Qualifiers::OCL_Weak:
983 case Qualifiers::OCL_Strong:
984 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000985 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000986 << ValType << FirstArg->getSourceRange();
987 return ExprError();
988 }
989
John McCallb45ae252011-10-05 07:41:44 +0000990 // Strip any qualifiers off ValType.
991 ValType = ValType.getUnqualifiedType();
992
Chandler Carruth8d13d222010-07-18 20:54:12 +0000993 // The majority of builtins return a value, but a few have special return
994 // types, so allow them to override appropriately below.
995 QualType ResultType = ValType;
996
Chris Lattner5caa3702009-05-08 06:58:22 +0000997 // We need to figure out which concrete builtin this maps onto. For example,
998 // __sync_fetch_and_add with a 2 byte object turns into
999 // __sync_fetch_and_add_2.
1000#define BUILTIN_ROW(x) \
1001 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1002 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner5caa3702009-05-08 06:58:22 +00001004 static const unsigned BuiltinIndices[][5] = {
1005 BUILTIN_ROW(__sync_fetch_and_add),
1006 BUILTIN_ROW(__sync_fetch_and_sub),
1007 BUILTIN_ROW(__sync_fetch_and_or),
1008 BUILTIN_ROW(__sync_fetch_and_and),
1009 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner5caa3702009-05-08 06:58:22 +00001011 BUILTIN_ROW(__sync_add_and_fetch),
1012 BUILTIN_ROW(__sync_sub_and_fetch),
1013 BUILTIN_ROW(__sync_and_and_fetch),
1014 BUILTIN_ROW(__sync_or_and_fetch),
1015 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner5caa3702009-05-08 06:58:22 +00001017 BUILTIN_ROW(__sync_val_compare_and_swap),
1018 BUILTIN_ROW(__sync_bool_compare_and_swap),
1019 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001020 BUILTIN_ROW(__sync_lock_release),
1021 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001022 };
Mike Stump1eb44332009-09-09 15:08:12 +00001023#undef BUILTIN_ROW
1024
Chris Lattner5caa3702009-05-08 06:58:22 +00001025 // Determine the index of the size.
1026 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001027 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001028 case 1: SizeIndex = 0; break;
1029 case 2: SizeIndex = 1; break;
1030 case 4: SizeIndex = 2; break;
1031 case 8: SizeIndex = 3; break;
1032 case 16: SizeIndex = 4; break;
1033 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1035 << FirstArg->getType() << FirstArg->getSourceRange();
1036 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001037 }
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Chris Lattner5caa3702009-05-08 06:58:22 +00001039 // Each of these builtins has one pointer argument, followed by some number of
1040 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1041 // that we ignore. Find out which row of BuiltinIndices to read from as well
1042 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001043 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001044 unsigned BuiltinIndex, NumFixed = 1;
1045 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001046 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001047 case Builtin::BI__sync_fetch_and_add:
1048 case Builtin::BI__sync_fetch_and_add_1:
1049 case Builtin::BI__sync_fetch_and_add_2:
1050 case Builtin::BI__sync_fetch_and_add_4:
1051 case Builtin::BI__sync_fetch_and_add_8:
1052 case Builtin::BI__sync_fetch_and_add_16:
1053 BuiltinIndex = 0;
1054 break;
1055
1056 case Builtin::BI__sync_fetch_and_sub:
1057 case Builtin::BI__sync_fetch_and_sub_1:
1058 case Builtin::BI__sync_fetch_and_sub_2:
1059 case Builtin::BI__sync_fetch_and_sub_4:
1060 case Builtin::BI__sync_fetch_and_sub_8:
1061 case Builtin::BI__sync_fetch_and_sub_16:
1062 BuiltinIndex = 1;
1063 break;
1064
1065 case Builtin::BI__sync_fetch_and_or:
1066 case Builtin::BI__sync_fetch_and_or_1:
1067 case Builtin::BI__sync_fetch_and_or_2:
1068 case Builtin::BI__sync_fetch_and_or_4:
1069 case Builtin::BI__sync_fetch_and_or_8:
1070 case Builtin::BI__sync_fetch_and_or_16:
1071 BuiltinIndex = 2;
1072 break;
1073
1074 case Builtin::BI__sync_fetch_and_and:
1075 case Builtin::BI__sync_fetch_and_and_1:
1076 case Builtin::BI__sync_fetch_and_and_2:
1077 case Builtin::BI__sync_fetch_and_and_4:
1078 case Builtin::BI__sync_fetch_and_and_8:
1079 case Builtin::BI__sync_fetch_and_and_16:
1080 BuiltinIndex = 3;
1081 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Douglas Gregora9766412011-11-28 16:30:08 +00001083 case Builtin::BI__sync_fetch_and_xor:
1084 case Builtin::BI__sync_fetch_and_xor_1:
1085 case Builtin::BI__sync_fetch_and_xor_2:
1086 case Builtin::BI__sync_fetch_and_xor_4:
1087 case Builtin::BI__sync_fetch_and_xor_8:
1088 case Builtin::BI__sync_fetch_and_xor_16:
1089 BuiltinIndex = 4;
1090 break;
1091
1092 case Builtin::BI__sync_add_and_fetch:
1093 case Builtin::BI__sync_add_and_fetch_1:
1094 case Builtin::BI__sync_add_and_fetch_2:
1095 case Builtin::BI__sync_add_and_fetch_4:
1096 case Builtin::BI__sync_add_and_fetch_8:
1097 case Builtin::BI__sync_add_and_fetch_16:
1098 BuiltinIndex = 5;
1099 break;
1100
1101 case Builtin::BI__sync_sub_and_fetch:
1102 case Builtin::BI__sync_sub_and_fetch_1:
1103 case Builtin::BI__sync_sub_and_fetch_2:
1104 case Builtin::BI__sync_sub_and_fetch_4:
1105 case Builtin::BI__sync_sub_and_fetch_8:
1106 case Builtin::BI__sync_sub_and_fetch_16:
1107 BuiltinIndex = 6;
1108 break;
1109
1110 case Builtin::BI__sync_and_and_fetch:
1111 case Builtin::BI__sync_and_and_fetch_1:
1112 case Builtin::BI__sync_and_and_fetch_2:
1113 case Builtin::BI__sync_and_and_fetch_4:
1114 case Builtin::BI__sync_and_and_fetch_8:
1115 case Builtin::BI__sync_and_and_fetch_16:
1116 BuiltinIndex = 7;
1117 break;
1118
1119 case Builtin::BI__sync_or_and_fetch:
1120 case Builtin::BI__sync_or_and_fetch_1:
1121 case Builtin::BI__sync_or_and_fetch_2:
1122 case Builtin::BI__sync_or_and_fetch_4:
1123 case Builtin::BI__sync_or_and_fetch_8:
1124 case Builtin::BI__sync_or_and_fetch_16:
1125 BuiltinIndex = 8;
1126 break;
1127
1128 case Builtin::BI__sync_xor_and_fetch:
1129 case Builtin::BI__sync_xor_and_fetch_1:
1130 case Builtin::BI__sync_xor_and_fetch_2:
1131 case Builtin::BI__sync_xor_and_fetch_4:
1132 case Builtin::BI__sync_xor_and_fetch_8:
1133 case Builtin::BI__sync_xor_and_fetch_16:
1134 BuiltinIndex = 9;
1135 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner5caa3702009-05-08 06:58:22 +00001137 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001138 case Builtin::BI__sync_val_compare_and_swap_1:
1139 case Builtin::BI__sync_val_compare_and_swap_2:
1140 case Builtin::BI__sync_val_compare_and_swap_4:
1141 case Builtin::BI__sync_val_compare_and_swap_8:
1142 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001143 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001144 NumFixed = 2;
1145 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001146
Chris Lattner5caa3702009-05-08 06:58:22 +00001147 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001148 case Builtin::BI__sync_bool_compare_and_swap_1:
1149 case Builtin::BI__sync_bool_compare_and_swap_2:
1150 case Builtin::BI__sync_bool_compare_and_swap_4:
1151 case Builtin::BI__sync_bool_compare_and_swap_8:
1152 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001153 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001154 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001155 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001156 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001157
1158 case Builtin::BI__sync_lock_test_and_set:
1159 case Builtin::BI__sync_lock_test_and_set_1:
1160 case Builtin::BI__sync_lock_test_and_set_2:
1161 case Builtin::BI__sync_lock_test_and_set_4:
1162 case Builtin::BI__sync_lock_test_and_set_8:
1163 case Builtin::BI__sync_lock_test_and_set_16:
1164 BuiltinIndex = 12;
1165 break;
1166
Chris Lattner5caa3702009-05-08 06:58:22 +00001167 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001168 case Builtin::BI__sync_lock_release_1:
1169 case Builtin::BI__sync_lock_release_2:
1170 case Builtin::BI__sync_lock_release_4:
1171 case Builtin::BI__sync_lock_release_8:
1172 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001173 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001174 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001175 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001176 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001177
1178 case Builtin::BI__sync_swap:
1179 case Builtin::BI__sync_swap_1:
1180 case Builtin::BI__sync_swap_2:
1181 case Builtin::BI__sync_swap_4:
1182 case Builtin::BI__sync_swap_8:
1183 case Builtin::BI__sync_swap_16:
1184 BuiltinIndex = 14;
1185 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001186 }
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Chris Lattner5caa3702009-05-08 06:58:22 +00001188 // Now that we know how many fixed arguments we expect, first check that we
1189 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001190 if (TheCall->getNumArgs() < 1+NumFixed) {
1191 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1192 << 0 << 1+NumFixed << TheCall->getNumArgs()
1193 << TheCall->getCallee()->getSourceRange();
1194 return ExprError();
1195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001197 // Get the decl for the concrete builtin from this, we can tell what the
1198 // concrete integer type we should convert to is.
1199 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1200 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1201 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001202 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001203 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1204 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001205
John McCallf871d0c2010-08-07 06:22:56 +00001206 // The first argument --- the pointer --- has a fixed type; we
1207 // deduce the types of the rest of the arguments accordingly. Walk
1208 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001209 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001210 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Chris Lattner5caa3702009-05-08 06:58:22 +00001212 // GCC does an implicit conversion to the pointer or integer ValType. This
1213 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001214 // Initialize the argument.
1215 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1216 ValType, /*consume*/ false);
1217 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001218 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001219 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner5caa3702009-05-08 06:58:22 +00001221 // Okay, we have something that *can* be converted to the right type. Check
1222 // to see if there is a potentially weird extension going on here. This can
1223 // happen when you do an atomic operation on something like an char* and
1224 // pass in 42. The 42 gets converted to char. This is even more strange
1225 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001226 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001227 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001228 }
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001230 ASTContext& Context = this->getASTContext();
1231
1232 // Create a new DeclRefExpr to refer to the new decl.
1233 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1234 Context,
1235 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001236 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001237 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001238 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001239 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001240 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001241 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Chris Lattner5caa3702009-05-08 06:58:22 +00001243 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001244 // FIXME: This loses syntactic information.
1245 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1246 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1247 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001248 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001250 // Change the result type of the call to match the original value type. This
1251 // is arbitrary, but the codegen for these builtins ins design to handle it
1252 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001253 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001254
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001255 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001256}
1257
Chris Lattner69039812009-02-18 06:01:06 +00001258/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001259/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001260/// Note: It might also make sense to do the UTF-16 conversion here (would
1261/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001262bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001263 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001264 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1265
Douglas Gregor5cee1192011-07-27 05:40:30 +00001266 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001267 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1268 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001269 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001270 }
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001272 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001273 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001274 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001275 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001276 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001277 UTF16 *ToPtr = &ToBuf[0];
1278
1279 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1280 &ToPtr, ToPtr + NumBytes,
1281 strictConversion);
1282 // Check for conversion failure.
1283 if (Result != conversionOK)
1284 Diag(Arg->getLocStart(),
1285 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1286 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001287 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001288}
1289
Chris Lattnerc27c6652007-12-20 00:05:45 +00001290/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1291/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001292bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1293 Expr *Fn = TheCall->getCallee();
1294 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001295 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001296 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001297 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1298 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001299 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001300 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001301 return true;
1302 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001303
1304 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001305 return Diag(TheCall->getLocEnd(),
1306 diag::err_typecheck_call_too_few_args_at_least)
1307 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001308 }
1309
John McCall5f8d6042011-08-27 01:09:30 +00001310 // Type-check the first argument normally.
1311 if (checkBuiltinArgument(*this, TheCall, 0))
1312 return true;
1313
Chris Lattnerc27c6652007-12-20 00:05:45 +00001314 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001315 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001316 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001317 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001318 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001319 else if (FunctionDecl *FD = getCurFunctionDecl())
1320 isVariadic = FD->isVariadic();
1321 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001322 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Chris Lattnerc27c6652007-12-20 00:05:45 +00001324 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001325 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1326 return true;
1327 }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Chris Lattner30ce3442007-12-19 23:59:04 +00001329 // Verify that the second argument to the builtin is the last argument of the
1330 // current function or method.
1331 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001332 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Anders Carlsson88cf2262008-02-11 04:20:54 +00001334 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1335 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001336 // FIXME: This isn't correct for methods (results in bogus warning).
1337 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001338 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001339 if (CurBlock)
1340 LastArg = *(CurBlock->TheDecl->param_end()-1);
1341 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001342 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001343 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001344 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001345 SecondArgIsLastNamedArgument = PV == LastArg;
1346 }
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Chris Lattner30ce3442007-12-19 23:59:04 +00001349 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001350 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001351 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1352 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001353}
Chris Lattner30ce3442007-12-19 23:59:04 +00001354
Chris Lattner1b9a0792007-12-20 00:26:33 +00001355/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1356/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001357bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1358 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001359 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001360 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001361 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001362 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001363 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001364 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001365 << SourceRange(TheCall->getArg(2)->getLocStart(),
1366 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001367
John Wiegley429bb272011-04-08 18:41:53 +00001368 ExprResult OrigArg0 = TheCall->getArg(0);
1369 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001370
Chris Lattner1b9a0792007-12-20 00:26:33 +00001371 // Do standard promotions between the two arguments, returning their common
1372 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001373 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001374 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1375 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001376
1377 // Make sure any conversions are pushed back into the call; this is
1378 // type safe since unordered compare builtins are declared as "_Bool
1379 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001380 TheCall->setArg(0, OrigArg0.get());
1381 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001382
John Wiegley429bb272011-04-08 18:41:53 +00001383 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001384 return false;
1385
Chris Lattner1b9a0792007-12-20 00:26:33 +00001386 // If the common type isn't a real floating type, then the arguments were
1387 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001388 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001389 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001390 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001391 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1392 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Chris Lattner1b9a0792007-12-20 00:26:33 +00001394 return false;
1395}
1396
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001397/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1398/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001399/// to check everything. We expect the last argument to be a floating point
1400/// value.
1401bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1402 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001403 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001404 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001405 if (TheCall->getNumArgs() > NumArgs)
1406 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001407 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001408 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001409 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001410 (*(TheCall->arg_end()-1))->getLocEnd());
1411
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001412 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Eli Friedman9ac6f622009-08-31 20:06:00 +00001414 if (OrigArg->isTypeDependent())
1415 return false;
1416
Chris Lattner81368fb2010-05-06 05:50:07 +00001417 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001418 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001419 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001420 diag::err_typecheck_call_invalid_unary_fp)
1421 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Chris Lattner81368fb2010-05-06 05:50:07 +00001423 // If this is an implicit conversion from float -> double, remove it.
1424 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1425 Expr *CastArg = Cast->getSubExpr();
1426 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1427 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1428 "promotion from float to double is the only expected cast here");
1429 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001430 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001431 }
1432 }
1433
Eli Friedman9ac6f622009-08-31 20:06:00 +00001434 return false;
1435}
1436
Eli Friedmand38617c2008-05-14 19:38:39 +00001437/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1438// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001439ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001440 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001441 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001442 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001443 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001444 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001445
Nate Begeman37b6a572010-06-08 00:16:34 +00001446 // Determine which of the following types of shufflevector we're checking:
1447 // 1) unary, vector mask: (lhs, mask)
1448 // 2) binary, vector mask: (lhs, rhs, mask)
1449 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1450 QualType resType = TheCall->getArg(0)->getType();
1451 unsigned numElements = 0;
1452
Douglas Gregorcde01732009-05-19 22:10:17 +00001453 if (!TheCall->getArg(0)->isTypeDependent() &&
1454 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001455 QualType LHSType = TheCall->getArg(0)->getType();
1456 QualType RHSType = TheCall->getArg(1)->getType();
1457
1458 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001459 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001460 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001461 TheCall->getArg(1)->getLocEnd());
1462 return ExprError();
1463 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001464
1465 numElements = LHSType->getAs<VectorType>()->getNumElements();
1466 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Nate Begeman37b6a572010-06-08 00:16:34 +00001468 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1469 // with mask. If so, verify that RHS is an integer vector type with the
1470 // same number of elts as lhs.
1471 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001472 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001473 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1474 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1475 << SourceRange(TheCall->getArg(1)->getLocStart(),
1476 TheCall->getArg(1)->getLocEnd());
1477 numResElements = numElements;
1478 }
1479 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001480 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001481 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001482 TheCall->getArg(1)->getLocEnd());
1483 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001484 } else if (numElements != numResElements) {
1485 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001486 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001487 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001488 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001489 }
1490
1491 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001492 if (TheCall->getArg(i)->isTypeDependent() ||
1493 TheCall->getArg(i)->isValueDependent())
1494 continue;
1495
Nate Begeman37b6a572010-06-08 00:16:34 +00001496 llvm::APSInt Result(32);
1497 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1498 return ExprError(Diag(TheCall->getLocStart(),
1499 diag::err_shufflevector_nonconstant_argument)
1500 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001501
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001502 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001503 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001504 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001505 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001506 }
1507
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001509
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001510 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001511 exprs.push_back(TheCall->getArg(i));
1512 TheCall->setArg(i, 0);
1513 }
1514
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001515 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001516 TheCall->getCallee()->getLocStart(),
1517 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001518}
Chris Lattner30ce3442007-12-19 23:59:04 +00001519
Daniel Dunbar4493f792008-07-21 22:59:13 +00001520/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1521// This is declared to take (const void*, ...) and can take two
1522// optional constant int args.
1523bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001524 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001525
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001526 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001527 return Diag(TheCall->getLocEnd(),
1528 diag::err_typecheck_call_too_many_args_at_most)
1529 << 0 /*function call*/ << 3 << NumArgs
1530 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001531
1532 // Argument 0 is checked for us and the remaining arguments must be
1533 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001534 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001535 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001536
1537 // We can't check the value of a dependent argument.
1538 if (Arg->isTypeDependent() || Arg->isValueDependent())
1539 continue;
1540
Eli Friedman9aef7262009-12-04 00:30:06 +00001541 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001542 if (SemaBuiltinConstantArg(TheCall, i, Result))
1543 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Daniel Dunbar4493f792008-07-21 22:59:13 +00001545 // FIXME: gcc issues a warning and rewrites these to 0. These
1546 // seems especially odd for the third argument since the default
1547 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001548 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001549 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001550 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001551 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001552 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001553 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001554 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001555 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001556 }
1557 }
1558
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001559 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001560}
1561
Eric Christopher691ebc32010-04-17 02:26:23 +00001562/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1563/// TheCall is a constant expression.
1564bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1565 llvm::APSInt &Result) {
1566 Expr *Arg = TheCall->getArg(ArgNum);
1567 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1568 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1569
1570 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1571
1572 if (!Arg->isIntegerConstantExpr(Result, Context))
1573 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001574 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001575
Chris Lattner21fb98e2009-09-23 06:06:36 +00001576 return false;
1577}
1578
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001579/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1580/// int type). This simply type checks that type is one of the defined
1581/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001582// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001583bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001584 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001585
1586 // We can't check the value of a dependent argument.
1587 if (TheCall->getArg(1)->isTypeDependent() ||
1588 TheCall->getArg(1)->isValueDependent())
1589 return false;
1590
Eric Christopher691ebc32010-04-17 02:26:23 +00001591 // Check constant-ness first.
1592 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1593 return true;
1594
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001595 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001596 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001597 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1598 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001599 }
1600
1601 return false;
1602}
1603
Eli Friedman586d6a82009-05-03 06:04:26 +00001604/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001605/// This checks that val is a constant 1.
1606bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1607 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001608 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001609
Eric Christopher691ebc32010-04-17 02:26:23 +00001610 // TODO: This is less than ideal. Overload this to take a value.
1611 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1612 return true;
1613
1614 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001615 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1616 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1617
1618 return false;
1619}
1620
Richard Smith831421f2012-06-25 20:30:08 +00001621// Determine if an expression is a string literal or constant string.
1622// If this function returns false on the arguments to a function expecting a
1623// format string, we will usually need to emit a warning.
1624// True string literals are then checked by CheckFormatString.
1625Sema::StringLiteralCheckType
1626Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1627 unsigned NumArgs, bool HasVAListArg,
1628 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001629 FormatStringType Type, VariadicCallType CallType,
1630 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001631 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001632 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001633 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001634
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001635 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001636
David Blaikiea73cdcb2012-02-10 21:07:25 +00001637 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1638 // Technically -Wformat-nonliteral does not warn about this case.
1639 // The behavior of printf and friends in this case is implementation
1640 // dependent. Ideally if the format string cannot be null then
1641 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001642 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001643
Ted Kremenekd30ef872009-01-12 23:09:09 +00001644 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001645 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001646 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001647 // The expression is a literal if both sub-expressions were, and it was
1648 // completely checked only if both sub-expressions were checked.
1649 const AbstractConditionalOperator *C =
1650 cast<AbstractConditionalOperator>(E);
1651 StringLiteralCheckType Left =
1652 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1653 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001654 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001655 if (Left == SLCT_NotALiteral)
1656 return SLCT_NotALiteral;
1657 StringLiteralCheckType Right =
1658 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1659 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001660 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001661 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001662 }
1663
1664 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001665 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1666 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001667 }
1668
John McCall56ca35d2011-02-17 10:25:35 +00001669 case Stmt::OpaqueValueExprClass:
1670 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1671 E = src;
1672 goto tryAgain;
1673 }
Richard Smith831421f2012-06-25 20:30:08 +00001674 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001675
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001676 case Stmt::PredefinedExprClass:
1677 // While __func__, etc., are technically not string literals, they
1678 // cannot contain format specifiers and thus are not a security
1679 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001680 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001681
Ted Kremenek082d9362009-03-20 21:35:28 +00001682 case Stmt::DeclRefExprClass: {
1683 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Ted Kremenek082d9362009-03-20 21:35:28 +00001685 // As an exception, do not flag errors for variables binding to
1686 // const string literals.
1687 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1688 bool isConstant = false;
1689 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001690
Ted Kremenek082d9362009-03-20 21:35:28 +00001691 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1692 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001693 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001694 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001695 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001696 } else if (T->isObjCObjectPointerType()) {
1697 // In ObjC, there is usually no "const ObjectPointer" type,
1698 // so don't check if the pointee type is constant.
1699 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001700 }
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Ted Kremenek082d9362009-03-20 21:35:28 +00001702 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001703 if (const Expr *Init = VD->getAnyInitializer()) {
1704 // Look through initializers like const char c[] = { "foo" }
1705 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1706 if (InitList->isStringLiteralInit())
1707 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1708 }
Richard Smith831421f2012-06-25 20:30:08 +00001709 return checkFormatStringExpr(Init, Args, NumArgs,
1710 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001711 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001712 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001713 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlssond966a552009-06-28 19:55:58 +00001716 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1717 // special check to see if the format string is a function parameter
1718 // of the function calling the printf function. If the function
1719 // has an attribute indicating it is a printf-like function, then we
1720 // should suppress warnings concerning non-literals being used in a call
1721 // to a vprintf function. For example:
1722 //
1723 // void
1724 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1725 // va_list ap;
1726 // va_start(ap, fmt);
1727 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1728 // ...
1729 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001730 if (HasVAListArg) {
1731 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1732 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1733 int PVIndex = PV->getFunctionScopeIndex() + 1;
1734 for (specific_attr_iterator<FormatAttr>
1735 i = ND->specific_attr_begin<FormatAttr>(),
1736 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1737 FormatAttr *PVFormat = *i;
1738 // adjust for implicit parameter
1739 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1740 if (MD->isInstance())
1741 ++PVIndex;
1742 // We also check if the formats are compatible.
1743 // We can't pass a 'scanf' string to a 'printf' function.
1744 if (PVIndex == PVFormat->getFormatIdx() &&
1745 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001746 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001747 }
1748 }
1749 }
1750 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001751 }
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Richard Smith831421f2012-06-25 20:30:08 +00001753 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001754 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001755
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001756 case Stmt::CallExprClass:
1757 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001758 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001759 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1760 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1761 unsigned ArgIndex = FA->getFormatIdx();
1762 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1763 if (MD->isInstance())
1764 --ArgIndex;
1765 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Richard Smith831421f2012-06-25 20:30:08 +00001767 return checkFormatStringExpr(Arg, Args, NumArgs,
1768 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001769 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001770 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1771 unsigned BuiltinID = FD->getBuiltinID();
1772 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1773 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1774 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001775 return checkFormatStringExpr(Arg, Args, NumArgs,
1776 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001777 firstDataArg, Type, CallType,
1778 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001779 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001780 }
1781 }
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Richard Smith831421f2012-06-25 20:30:08 +00001783 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001784 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001785 case Stmt::ObjCStringLiteralClass:
1786 case Stmt::StringLiteralClass: {
1787 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Ted Kremenek082d9362009-03-20 21:35:28 +00001789 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001790 StrE = ObjCFExpr->getString();
1791 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001792 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Ted Kremenekd30ef872009-01-12 23:09:09 +00001794 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001795 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001796 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001797 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Richard Smith831421f2012-06-25 20:30:08 +00001800 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Ted Kremenek082d9362009-03-20 21:35:28 +00001803 default:
Richard Smith831421f2012-06-25 20:30:08 +00001804 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001805 }
1806}
1807
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001808void
Mike Stump1eb44332009-09-09 15:08:12 +00001809Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001810 const Expr * const *ExprArgs,
1811 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001812 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1813 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001814 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001815 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001816 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001817 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001818 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001819 }
1820}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001821
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001822Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1823 return llvm::StringSwitch<FormatStringType>(Format->getType())
1824 .Case("scanf", FST_Scanf)
1825 .Cases("printf", "printf0", FST_Printf)
1826 .Cases("NSString", "CFString", FST_NSString)
1827 .Case("strftime", FST_Strftime)
1828 .Case("strfmon", FST_Strfmon)
1829 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1830 .Default(FST_Unknown);
1831}
1832
Jordan Roseddcfbc92012-07-19 18:10:23 +00001833/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001834/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001835/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001836bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001837 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001838 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001839 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001840 FormatStringInfo FSI;
1841 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1842 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1843 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001844 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001845 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001846}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001847
Richard Smith831421f2012-06-25 20:30:08 +00001848bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001849 bool HasVAListArg, unsigned format_idx,
1850 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001851 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001852 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001853 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001854 if (format_idx >= NumArgs) {
1855 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001856 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001859 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Chris Lattner59907c42007-08-10 20:18:51 +00001861 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001862 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001863 // Dynamically generated format strings are difficult to
1864 // automatically vet at compile time. Requiring that format strings
1865 // are string literals: (1) permits the checking of format strings by
1866 // the compiler and thereby (2) can practically remove the source of
1867 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001868
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001870 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001871 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001872 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001873 StringLiteralCheckType CT =
1874 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001875 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001876 if (CT != SLCT_NotALiteral)
1877 // Literal format string found, check done!
1878 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001879
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001880 // Strftime is particular as it always uses a single 'time' argument,
1881 // so it is safe to pass a non-literal string.
1882 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001883 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001884
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001885 // Do not emit diag when the string param is a macro expansion and the
1886 // format is either NSString or CFString. This is a hack to prevent
1887 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1888 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001889 if (Type == FST_NSString &&
1890 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001891 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001892
Chris Lattner655f1412009-04-29 04:59:47 +00001893 // If there are no arguments specified, warn with -Wformat-security, otherwise
1894 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001895 if (NumArgs == format_idx+1)
1896 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001897 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001898 << OrigFormatExpr->getSourceRange();
1899 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001900 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001901 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001902 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001903 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001904}
Ted Kremenek71895b92007-08-14 17:39:48 +00001905
Ted Kremeneke0e53132010-01-28 23:39:18 +00001906namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001907class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1908protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001909 Sema &S;
1910 const StringLiteral *FExpr;
1911 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001912 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001913 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001914 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001915 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001916 const Expr * const *Args;
1917 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001918 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001919 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001920 bool usesPositionalArgs;
1921 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001922 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001923 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001924public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001925 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001926 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001927 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001928 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001929 unsigned formatIdx, bool inFunctionCall,
1930 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001931 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001932 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1933 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001934 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001935 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001936 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001937 CoveredArgs.resize(numDataArgs);
1938 CoveredArgs.reset();
1939 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001940
Ted Kremenek07d161f2010-01-29 01:50:07 +00001941 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001942
Ted Kremenek826a3452010-07-16 02:11:22 +00001943 void HandleIncompleteSpecifier(const char *startSpecifier,
1944 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001945
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001946 void HandleInvalidLengthModifier(
1947 const analyze_format_string::FormatSpecifier &FS,
1948 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001949 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001950
Hans Wennborg76517422012-02-22 10:17:01 +00001951 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001952 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001953 const char *startSpecifier, unsigned specifierLen);
1954
1955 void HandleNonStandardConversionSpecifier(
1956 const analyze_format_string::ConversionSpecifier &CS,
1957 const char *startSpecifier, unsigned specifierLen);
1958
Hans Wennborgf8562642012-03-09 10:10:54 +00001959 virtual void HandlePosition(const char *startPos, unsigned posLen);
1960
Ted Kremenekefaff192010-02-27 01:41:03 +00001961 virtual void HandleInvalidPosition(const char *startSpecifier,
1962 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001963 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001964
1965 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1966
Ted Kremeneke0e53132010-01-28 23:39:18 +00001967 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001968
Richard Trieu55733de2011-10-28 00:41:25 +00001969 template <typename Range>
1970 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1971 const Expr *ArgumentExpr,
1972 PartialDiagnostic PDiag,
1973 SourceLocation StringLoc,
1974 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001975 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001976
Ted Kremenek826a3452010-07-16 02:11:22 +00001977protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001978 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1979 const char *startSpec,
1980 unsigned specifierLen,
1981 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001982
1983 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1984 const char *startSpec,
1985 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001986
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001987 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001988 CharSourceRange getSpecifierRange(const char *startSpecifier,
1989 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001990 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001991
Ted Kremenek0d277352010-01-29 01:06:55 +00001992 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001993
1994 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1995 const analyze_format_string::ConversionSpecifier &CS,
1996 const char *startSpecifier, unsigned specifierLen,
1997 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001998
1999 template <typename Range>
2000 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2001 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002002 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002003
2004 void CheckPositionalAndNonpositionalArgs(
2005 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002006};
2007}
2008
Ted Kremenek826a3452010-07-16 02:11:22 +00002009SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002010 return OrigFormatExpr->getSourceRange();
2011}
2012
Ted Kremenek826a3452010-07-16 02:11:22 +00002013CharSourceRange CheckFormatHandler::
2014getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002015 SourceLocation Start = getLocationOfByte(startSpecifier);
2016 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2017
2018 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002019 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002020
2021 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002022}
2023
Ted Kremenek826a3452010-07-16 02:11:22 +00002024SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002025 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002026}
2027
Ted Kremenek826a3452010-07-16 02:11:22 +00002028void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2029 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002030 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2031 getLocationOfByte(startSpecifier),
2032 /*IsStringLocation*/true,
2033 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002034}
2035
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002036void CheckFormatHandler::HandleInvalidLengthModifier(
2037 const analyze_format_string::FormatSpecifier &FS,
2038 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002039 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002040 using namespace analyze_format_string;
2041
2042 const LengthModifier &LM = FS.getLengthModifier();
2043 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2044
2045 // See if we know how to fix this length modifier.
2046 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2047 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002048 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002049 getLocationOfByte(LM.getStart()),
2050 /*IsStringLocation*/true,
2051 getSpecifierRange(startSpecifier, specifierLen));
2052
2053 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2054 << FixedLM->toString()
2055 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2056
2057 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002058 FixItHint Hint;
2059 if (DiagID == diag::warn_format_nonsensical_length)
2060 Hint = FixItHint::CreateRemoval(LMRange);
2061
2062 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002063 getLocationOfByte(LM.getStart()),
2064 /*IsStringLocation*/true,
2065 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002066 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002067 }
2068}
2069
Hans Wennborg76517422012-02-22 10:17:01 +00002070void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002071 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002072 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002073 using namespace analyze_format_string;
2074
2075 const LengthModifier &LM = FS.getLengthModifier();
2076 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2077
2078 // See if we know how to fix this length modifier.
2079 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2080 if (FixedLM) {
2081 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2082 << LM.toString() << 0,
2083 getLocationOfByte(LM.getStart()),
2084 /*IsStringLocation*/true,
2085 getSpecifierRange(startSpecifier, specifierLen));
2086
2087 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2088 << FixedLM->toString()
2089 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2090
2091 } else {
2092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2093 << LM.toString() << 0,
2094 getLocationOfByte(LM.getStart()),
2095 /*IsStringLocation*/true,
2096 getSpecifierRange(startSpecifier, specifierLen));
2097 }
Hans Wennborg76517422012-02-22 10:17:01 +00002098}
2099
2100void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2101 const analyze_format_string::ConversionSpecifier &CS,
2102 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002103 using namespace analyze_format_string;
2104
2105 // See if we know how to fix this conversion specifier.
2106 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2107 if (FixedCS) {
2108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2109 << CS.toString() << /*conversion specifier*/1,
2110 getLocationOfByte(CS.getStart()),
2111 /*IsStringLocation*/true,
2112 getSpecifierRange(startSpecifier, specifierLen));
2113
2114 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2115 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2116 << FixedCS->toString()
2117 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2118 } else {
2119 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2120 << CS.toString() << /*conversion specifier*/1,
2121 getLocationOfByte(CS.getStart()),
2122 /*IsStringLocation*/true,
2123 getSpecifierRange(startSpecifier, specifierLen));
2124 }
Hans Wennborg76517422012-02-22 10:17:01 +00002125}
2126
Hans Wennborgf8562642012-03-09 10:10:54 +00002127void CheckFormatHandler::HandlePosition(const char *startPos,
2128 unsigned posLen) {
2129 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2130 getLocationOfByte(startPos),
2131 /*IsStringLocation*/true,
2132 getSpecifierRange(startPos, posLen));
2133}
2134
Ted Kremenekefaff192010-02-27 01:41:03 +00002135void
Ted Kremenek826a3452010-07-16 02:11:22 +00002136CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2137 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002138 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2139 << (unsigned) p,
2140 getLocationOfByte(startPos), /*IsStringLocation*/true,
2141 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002142}
2143
Ted Kremenek826a3452010-07-16 02:11:22 +00002144void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002145 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002146 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2147 getLocationOfByte(startPos),
2148 /*IsStringLocation*/true,
2149 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002150}
2151
Ted Kremenek826a3452010-07-16 02:11:22 +00002152void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002153 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002154 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002155 EmitFormatDiagnostic(
2156 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2157 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2158 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002159 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002160}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002161
Jordan Rose48716662012-07-19 18:10:08 +00002162// Note that this may return NULL if there was an error parsing or building
2163// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002164const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002165 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002166}
2167
2168void CheckFormatHandler::DoneProcessing() {
2169 // Does the number of data arguments exceed the number of
2170 // format conversions in the format string?
2171 if (!HasVAListArg) {
2172 // Find any arguments that weren't covered.
2173 CoveredArgs.flip();
2174 signed notCoveredArg = CoveredArgs.find_first();
2175 if (notCoveredArg >= 0) {
2176 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002177 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2178 SourceLocation Loc = E->getLocStart();
2179 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2180 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2181 Loc, /*IsStringLocation*/false,
2182 getFormatStringRange());
2183 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002184 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002185 }
2186 }
2187}
2188
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002189bool
2190CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2191 SourceLocation Loc,
2192 const char *startSpec,
2193 unsigned specifierLen,
2194 const char *csStart,
2195 unsigned csLen) {
2196
2197 bool keepGoing = true;
2198 if (argIndex < NumDataArgs) {
2199 // Consider the argument coverered, even though the specifier doesn't
2200 // make sense.
2201 CoveredArgs.set(argIndex);
2202 }
2203 else {
2204 // If argIndex exceeds the number of data arguments we
2205 // don't issue a warning because that is just a cascade of warnings (and
2206 // they may have intended '%%' anyway). We don't want to continue processing
2207 // the format string after this point, however, as we will like just get
2208 // gibberish when trying to match arguments.
2209 keepGoing = false;
2210 }
2211
Richard Trieu55733de2011-10-28 00:41:25 +00002212 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2213 << StringRef(csStart, csLen),
2214 Loc, /*IsStringLocation*/true,
2215 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002216
2217 return keepGoing;
2218}
2219
Richard Trieu55733de2011-10-28 00:41:25 +00002220void
2221CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2222 const char *startSpec,
2223 unsigned specifierLen) {
2224 EmitFormatDiagnostic(
2225 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2226 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2227}
2228
Ted Kremenek666a1972010-07-26 19:45:42 +00002229bool
2230CheckFormatHandler::CheckNumArgs(
2231 const analyze_format_string::FormatSpecifier &FS,
2232 const analyze_format_string::ConversionSpecifier &CS,
2233 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2234
2235 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002236 PartialDiagnostic PDiag = FS.usesPositionalArg()
2237 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2238 << (argIndex+1) << NumDataArgs)
2239 : S.PDiag(diag::warn_printf_insufficient_data_args);
2240 EmitFormatDiagnostic(
2241 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2242 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002243 return false;
2244 }
2245 return true;
2246}
2247
Richard Trieu55733de2011-10-28 00:41:25 +00002248template<typename Range>
2249void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2250 SourceLocation Loc,
2251 bool IsStringLocation,
2252 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002253 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002254 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002255 Loc, IsStringLocation, StringRange, FixIt);
2256}
2257
2258/// \brief If the format string is not within the funcion call, emit a note
2259/// so that the function call and string are in diagnostic messages.
2260///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002261/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002262/// call and only one diagnostic message will be produced. Otherwise, an
2263/// extra note will be emitted pointing to location of the format string.
2264///
2265/// \param ArgumentExpr the expression that is passed as the format string
2266/// argument in the function call. Used for getting locations when two
2267/// diagnostics are emitted.
2268///
2269/// \param PDiag the callee should already have provided any strings for the
2270/// diagnostic message. This function only adds locations and fixits
2271/// to diagnostics.
2272///
2273/// \param Loc primary location for diagnostic. If two diagnostics are
2274/// required, one will be at Loc and a new SourceLocation will be created for
2275/// the other one.
2276///
2277/// \param IsStringLocation if true, Loc points to the format string should be
2278/// used for the note. Otherwise, Loc points to the argument list and will
2279/// be used with PDiag.
2280///
2281/// \param StringRange some or all of the string to highlight. This is
2282/// templated so it can accept either a CharSourceRange or a SourceRange.
2283///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002284/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002285template<typename Range>
2286void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2287 const Expr *ArgumentExpr,
2288 PartialDiagnostic PDiag,
2289 SourceLocation Loc,
2290 bool IsStringLocation,
2291 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002292 ArrayRef<FixItHint> FixIt) {
2293 if (InFunctionCall) {
2294 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2295 D << StringRange;
2296 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2297 I != E; ++I) {
2298 D << *I;
2299 }
2300 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002301 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2302 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002303
2304 const Sema::SemaDiagnosticBuilder &Note =
2305 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2306 diag::note_format_string_defined);
2307
2308 Note << StringRange;
2309 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2310 I != E; ++I) {
2311 Note << *I;
2312 }
Richard Trieu55733de2011-10-28 00:41:25 +00002313 }
2314}
2315
Ted Kremenek826a3452010-07-16 02:11:22 +00002316//===--- CHECK: Printf format string checking ------------------------------===//
2317
2318namespace {
2319class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002320 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002321public:
2322 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2323 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002324 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002325 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002326 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002327 unsigned formatIdx, bool inFunctionCall,
2328 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002329 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002330 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002331 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2332 {}
2333
Ted Kremenek826a3452010-07-16 02:11:22 +00002334
2335 bool HandleInvalidPrintfConversionSpecifier(
2336 const analyze_printf::PrintfSpecifier &FS,
2337 const char *startSpecifier,
2338 unsigned specifierLen);
2339
2340 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2341 const char *startSpecifier,
2342 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002343 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2344 const char *StartSpecifier,
2345 unsigned SpecifierLen,
2346 const Expr *E);
2347
Ted Kremenek826a3452010-07-16 02:11:22 +00002348 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2349 const char *startSpecifier, unsigned specifierLen);
2350 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2351 const analyze_printf::OptionalAmount &Amt,
2352 unsigned type,
2353 const char *startSpecifier, unsigned specifierLen);
2354 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2355 const analyze_printf::OptionalFlag &flag,
2356 const char *startSpecifier, unsigned specifierLen);
2357 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2358 const analyze_printf::OptionalFlag &ignoredFlag,
2359 const analyze_printf::OptionalFlag &flag,
2360 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002361 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002362 const Expr *E, const CharSourceRange &CSR);
2363
Ted Kremenek826a3452010-07-16 02:11:22 +00002364};
2365}
2366
2367bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2368 const analyze_printf::PrintfSpecifier &FS,
2369 const char *startSpecifier,
2370 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002371 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002372 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002373
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002374 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2375 getLocationOfByte(CS.getStart()),
2376 startSpecifier, specifierLen,
2377 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002378}
2379
Ted Kremenek826a3452010-07-16 02:11:22 +00002380bool CheckPrintfHandler::HandleAmount(
2381 const analyze_format_string::OptionalAmount &Amt,
2382 unsigned k, const char *startSpecifier,
2383 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002384
2385 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002386 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002387 unsigned argIndex = Amt.getArgIndex();
2388 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002389 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2390 << k,
2391 getLocationOfByte(Amt.getStart()),
2392 /*IsStringLocation*/true,
2393 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002394 // Don't do any more checking. We will just emit
2395 // spurious errors.
2396 return false;
2397 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002398
Ted Kremenek0d277352010-01-29 01:06:55 +00002399 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002400 // Although not in conformance with C99, we also allow the argument to be
2401 // an 'unsigned int' as that is a reasonably safe case. GCC also
2402 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002403 CoveredArgs.set(argIndex);
2404 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002405 if (!Arg)
2406 return false;
2407
Ted Kremenek0d277352010-01-29 01:06:55 +00002408 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002409
Hans Wennborgf3749f42012-08-07 08:11:26 +00002410 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2411 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002412
Hans Wennborgf3749f42012-08-07 08:11:26 +00002413 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002414 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002415 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002416 << T << Arg->getSourceRange(),
2417 getLocationOfByte(Amt.getStart()),
2418 /*IsStringLocation*/true,
2419 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002420 // Don't do any more checking. We will just emit
2421 // spurious errors.
2422 return false;
2423 }
2424 }
2425 }
2426 return true;
2427}
Ted Kremenek0d277352010-01-29 01:06:55 +00002428
Tom Caree4ee9662010-06-17 19:00:27 +00002429void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002430 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002431 const analyze_printf::OptionalAmount &Amt,
2432 unsigned type,
2433 const char *startSpecifier,
2434 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002435 const analyze_printf::PrintfConversionSpecifier &CS =
2436 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002437
Richard Trieu55733de2011-10-28 00:41:25 +00002438 FixItHint fixit =
2439 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2440 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2441 Amt.getConstantLength()))
2442 : FixItHint();
2443
2444 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2445 << type << CS.toString(),
2446 getLocationOfByte(Amt.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen),
2449 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002450}
2451
Ted Kremenek826a3452010-07-16 02:11:22 +00002452void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002453 const analyze_printf::OptionalFlag &flag,
2454 const char *startSpecifier,
2455 unsigned specifierLen) {
2456 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002457 const analyze_printf::PrintfConversionSpecifier &CS =
2458 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2460 << flag.toString() << CS.toString(),
2461 getLocationOfByte(flag.getPosition()),
2462 /*IsStringLocation*/true,
2463 getSpecifierRange(startSpecifier, specifierLen),
2464 FixItHint::CreateRemoval(
2465 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002466}
2467
2468void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002469 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002470 const analyze_printf::OptionalFlag &ignoredFlag,
2471 const analyze_printf::OptionalFlag &flag,
2472 const char *startSpecifier,
2473 unsigned specifierLen) {
2474 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2476 << ignoredFlag.toString() << flag.toString(),
2477 getLocationOfByte(ignoredFlag.getPosition()),
2478 /*IsStringLocation*/true,
2479 getSpecifierRange(startSpecifier, specifierLen),
2480 FixItHint::CreateRemoval(
2481 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002482}
2483
Richard Smith831421f2012-06-25 20:30:08 +00002484// Determines if the specified is a C++ class or struct containing
2485// a member with the specified name and kind (e.g. a CXXMethodDecl named
2486// "c_str()").
2487template<typename MemberKind>
2488static llvm::SmallPtrSet<MemberKind*, 1>
2489CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2490 const RecordType *RT = Ty->getAs<RecordType>();
2491 llvm::SmallPtrSet<MemberKind*, 1> Results;
2492
2493 if (!RT)
2494 return Results;
2495 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2496 if (!RD)
2497 return Results;
2498
2499 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2500 Sema::LookupMemberName);
2501
2502 // We just need to include all members of the right kind turned up by the
2503 // filter, at this point.
2504 if (S.LookupQualifiedName(R, RT->getDecl()))
2505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2506 NamedDecl *decl = (*I)->getUnderlyingDecl();
2507 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2508 Results.insert(FK);
2509 }
2510 return Results;
2511}
2512
2513// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002514// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002515// Returns true when a c_str() conversion method is found.
2516bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002517 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002518 const CharSourceRange &CSR) {
2519 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2520
2521 MethodSet Results =
2522 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2523
2524 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2525 MI != ME; ++MI) {
2526 const CXXMethodDecl *Method = *MI;
2527 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002528 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002529 // FIXME: Suggest parens if the expression needs them.
2530 SourceLocation EndLoc =
2531 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2532 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2533 << "c_str()"
2534 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2535 return true;
2536 }
2537 }
2538
2539 return false;
2540}
2541
Ted Kremeneke0e53132010-01-28 23:39:18 +00002542bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002543CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002544 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002545 const char *startSpecifier,
2546 unsigned specifierLen) {
2547
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002548 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002549 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002550 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002551
Ted Kremenekbaa40062010-07-19 22:01:06 +00002552 if (FS.consumesDataArgument()) {
2553 if (atFirstArg) {
2554 atFirstArg = false;
2555 usesPositionalArgs = FS.usesPositionalArg();
2556 }
2557 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002558 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2559 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002560 return false;
2561 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002562 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002563
Ted Kremenekefaff192010-02-27 01:41:03 +00002564 // First check if the field width, precision, and conversion specifier
2565 // have matching data arguments.
2566 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2567 startSpecifier, specifierLen)) {
2568 return false;
2569 }
2570
2571 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2572 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002573 return false;
2574 }
2575
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002576 if (!CS.consumesDataArgument()) {
2577 // FIXME: Technically specifying a precision or field width here
2578 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002579 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002580 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002581
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002582 // Consume the argument.
2583 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002584 if (argIndex < NumDataArgs) {
2585 // The check to see if the argIndex is valid will come later.
2586 // We set the bit here because we may exit early from this
2587 // function if we encounter some other error.
2588 CoveredArgs.set(argIndex);
2589 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002590
2591 // Check for using an Objective-C specific conversion specifier
2592 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002593 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002594 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2595 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002596 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002597
Tom Caree4ee9662010-06-17 19:00:27 +00002598 // Check for invalid use of field width
2599 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002600 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002601 startSpecifier, specifierLen);
2602 }
2603
2604 // Check for invalid use of precision
2605 if (!FS.hasValidPrecision()) {
2606 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2607 startSpecifier, specifierLen);
2608 }
2609
2610 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002611 if (!FS.hasValidThousandsGroupingPrefix())
2612 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002613 if (!FS.hasValidLeadingZeros())
2614 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2615 if (!FS.hasValidPlusPrefix())
2616 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002617 if (!FS.hasValidSpacePrefix())
2618 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002619 if (!FS.hasValidAlternativeForm())
2620 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2621 if (!FS.hasValidLeftJustified())
2622 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2623
2624 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002625 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2626 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2627 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002628 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2629 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2630 startSpecifier, specifierLen);
2631
2632 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002633 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002634 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2635 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002636 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002637 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002638 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002639 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2640 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002641
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002642 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2643 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2644
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002645 // The remaining checks depend on the data arguments.
2646 if (HasVAListArg)
2647 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002648
Ted Kremenek666a1972010-07-26 19:45:42 +00002649 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002650 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002651
Jordan Rose48716662012-07-19 18:10:08 +00002652 const Expr *Arg = getDataArg(argIndex);
2653 if (!Arg)
2654 return true;
2655
2656 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002657}
2658
Jordan Roseec087352012-09-05 22:56:26 +00002659static bool requiresParensToAddCast(const Expr *E) {
2660 // FIXME: We should have a general way to reason about operator
2661 // precedence and whether parens are actually needed here.
2662 // Take care of a few common cases where they aren't.
2663 const Expr *Inside = E->IgnoreImpCasts();
2664 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2665 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2666
2667 switch (Inside->getStmtClass()) {
2668 case Stmt::ArraySubscriptExprClass:
2669 case Stmt::CallExprClass:
2670 case Stmt::DeclRefExprClass:
2671 case Stmt::MemberExprClass:
2672 case Stmt::ObjCIvarRefExprClass:
2673 case Stmt::ObjCMessageExprClass:
2674 case Stmt::ObjCPropertyRefExprClass:
2675 case Stmt::ParenExprClass:
2676 case Stmt::UnaryOperatorClass:
2677 return false;
2678 default:
2679 return true;
2680 }
2681}
2682
Richard Smith831421f2012-06-25 20:30:08 +00002683bool
2684CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2685 const char *StartSpecifier,
2686 unsigned SpecifierLen,
2687 const Expr *E) {
2688 using namespace analyze_format_string;
2689 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002690 // Now type check the data expression that matches the
2691 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002692 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2693 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002694 if (!AT.isValid())
2695 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002696
2697 QualType IntendedTy = E->getType();
2698 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002699 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002700
Jordan Rose614a8652012-09-05 22:56:19 +00002701 // Look through argument promotions for our error message's reported type.
2702 // This includes the integral and floating promotions, but excludes array
2703 // and function pointer decay; seeing that an argument intended to be a
2704 // string has type 'char [6]' is probably more confusing than 'char *'.
2705 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2706 if (ICE->getCastKind() == CK_IntegralCast ||
2707 ICE->getCastKind() == CK_FloatingCast) {
2708 E = ICE->getSubExpr();
Jordan Roseec087352012-09-05 22:56:26 +00002709 IntendedTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002710
2711 // Check if we didn't match because of an implicit cast from a 'char'
2712 // or 'short' to an 'int'. This is done because printf is a varargs
2713 // function.
2714 if (ICE->getType() == S.Context.IntTy ||
2715 ICE->getType() == S.Context.UnsignedIntTy) {
2716 // All further checking is done on the subexpression.
Jordan Roseec087352012-09-05 22:56:26 +00002717 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002718 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002719 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002720 }
Jordan Rose614a8652012-09-05 22:56:19 +00002721 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002722
Jordan Roseec087352012-09-05 22:56:26 +00002723 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2724 // Special-case some of Darwin's platform-independence types.
2725 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2726 StringRef Name = UserTy->getDecl()->getName();
2727 IntendedTy = llvm::StringSwitch<QualType>(Name)
2728 .Case("NSInteger", S.Context.LongTy)
2729 .Case("NSUInteger", S.Context.UnsignedLongTy)
2730 .Case("SInt32", S.Context.IntTy)
2731 .Case("UInt32", S.Context.UnsignedIntTy)
2732 .Default(IntendedTy);
2733 }
2734 }
2735
Jordan Rose614a8652012-09-05 22:56:19 +00002736 // We may be able to offer a FixItHint if it is a supported type.
2737 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002738 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002739 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002740
Jordan Rose614a8652012-09-05 22:56:19 +00002741 if (success) {
2742 // Get the fix string from the fixed format specifier
2743 SmallString<16> buf;
2744 llvm::raw_svector_ostream os(buf);
2745 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002746
Jordan Roseec087352012-09-05 22:56:26 +00002747 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2748
2749 if (IntendedTy != E->getType()) {
2750 // The canonical type for formatting this value is different from the
2751 // actual type of the expression. (This occurs, for example, with Darwin's
2752 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2753 // should be printed as 'long' for 64-bit compatibility.)
2754 // Rather than emitting a normal format/argument mismatch, we want to
2755 // add a cast to the recommended type (and correct the format string
2756 // if necessary).
2757 SmallString<16> CastBuf;
2758 llvm::raw_svector_ostream CastFix(CastBuf);
2759 CastFix << "(";
2760 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2761 CastFix << ")";
2762
2763 SmallVector<FixItHint,4> Hints;
2764 if (!AT.matchesType(S.Context, IntendedTy))
2765 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2766
2767 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2768 // If there's already a cast present, just replace it.
2769 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2770 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2771
2772 } else if (!requiresParensToAddCast(E)) {
2773 // If the expression has high enough precedence,
2774 // just write the C-style cast.
2775 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2776 CastFix.str()));
2777 } else {
2778 // Otherwise, add parens around the expression as well as the cast.
2779 CastFix << "(";
2780 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2781 CastFix.str()));
2782
2783 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2784 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2785 }
2786
2787 // We extract the name from the typedef because we don't want to show
2788 // the underlying type in the diagnostic.
2789 const TypedefType *UserTy = cast<TypedefType>(E->getType());
2790 StringRef Name = UserTy->getDecl()->getName();
2791
2792 // Finally, emit the diagnostic.
2793 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2794 << Name << IntendedTy
2795 << E->getSourceRange(),
2796 E->getLocStart(), /*IsStringLocation=*/false,
2797 SpecRange, Hints);
2798 } else {
2799 EmitFormatDiagnostic(
2800 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2801 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2802 << E->getSourceRange(),
2803 E->getLocStart(),
2804 /*IsStringLocation*/false,
2805 SpecRange,
2806 FixItHint::CreateReplacement(SpecRange, os.str()));
2807 }
Jordan Rose614a8652012-09-05 22:56:19 +00002808 } else {
2809 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2810 SpecifierLen);
2811 // Since the warning for passing non-POD types to variadic functions
2812 // was deferred until now, we emit a warning for non-POD
2813 // arguments here.
2814 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2815 unsigned DiagKind;
2816 if (E->getType()->isObjCObjectType())
2817 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2818 else
2819 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2820
2821 EmitFormatDiagnostic(
2822 S.PDiag(DiagKind)
2823 << S.getLangOpts().CPlusPlus0x
2824 << E->getType()
2825 << CallType
2826 << AT.getRepresentativeTypeName(S.Context)
2827 << CSR
2828 << E->getSourceRange(),
2829 E->getLocStart(), /*IsStringLocation*/false, CSR);
2830
2831 checkForCStrMembers(AT, E, CSR);
2832 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002833 EmitFormatDiagnostic(
2834 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002835 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Jordan Rose614a8652012-09-05 22:56:19 +00002836 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002837 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002838 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002839 }
2840
Ted Kremeneke0e53132010-01-28 23:39:18 +00002841 return true;
2842}
2843
Ted Kremenek826a3452010-07-16 02:11:22 +00002844//===--- CHECK: Scanf format string checking ------------------------------===//
2845
2846namespace {
2847class CheckScanfHandler : public CheckFormatHandler {
2848public:
2849 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2850 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002851 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002852 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002853 unsigned formatIdx, bool inFunctionCall,
2854 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002855 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002856 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002857 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2858 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002859
2860 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2861 const char *startSpecifier,
2862 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002863
2864 bool HandleInvalidScanfConversionSpecifier(
2865 const analyze_scanf::ScanfSpecifier &FS,
2866 const char *startSpecifier,
2867 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002868
2869 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002870};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002871}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002872
Ted Kremenekb7c21012010-07-16 18:28:03 +00002873void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2874 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002875 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2876 getLocationOfByte(end), /*IsStringLocation*/true,
2877 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002878}
2879
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002880bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2881 const analyze_scanf::ScanfSpecifier &FS,
2882 const char *startSpecifier,
2883 unsigned specifierLen) {
2884
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002885 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002886 FS.getConversionSpecifier();
2887
2888 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2889 getLocationOfByte(CS.getStart()),
2890 startSpecifier, specifierLen,
2891 CS.getStart(), CS.getLength());
2892}
2893
Ted Kremenek826a3452010-07-16 02:11:22 +00002894bool CheckScanfHandler::HandleScanfSpecifier(
2895 const analyze_scanf::ScanfSpecifier &FS,
2896 const char *startSpecifier,
2897 unsigned specifierLen) {
2898
2899 using namespace analyze_scanf;
2900 using namespace analyze_format_string;
2901
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002902 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002903
Ted Kremenekbaa40062010-07-19 22:01:06 +00002904 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2905 // be used to decide if we are using positional arguments consistently.
2906 if (FS.consumesDataArgument()) {
2907 if (atFirstArg) {
2908 atFirstArg = false;
2909 usesPositionalArgs = FS.usesPositionalArg();
2910 }
2911 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002912 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2913 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002914 return false;
2915 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002916 }
2917
2918 // Check if the field with is non-zero.
2919 const OptionalAmount &Amt = FS.getFieldWidth();
2920 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2921 if (Amt.getConstantAmount() == 0) {
2922 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2923 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002924 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2925 getLocationOfByte(Amt.getStart()),
2926 /*IsStringLocation*/true, R,
2927 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002928 }
2929 }
2930
2931 if (!FS.consumesDataArgument()) {
2932 // FIXME: Technically specifying a precision or field width here
2933 // makes no sense. Worth issuing a warning at some point.
2934 return true;
2935 }
2936
2937 // Consume the argument.
2938 unsigned argIndex = FS.getArgIndex();
2939 if (argIndex < NumDataArgs) {
2940 // The check to see if the argIndex is valid will come later.
2941 // We set the bit here because we may exit early from this
2942 // function if we encounter some other error.
2943 CoveredArgs.set(argIndex);
2944 }
2945
Ted Kremenek1e51c202010-07-20 20:04:47 +00002946 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002947 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002948 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2949 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002950 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002951 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002952 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002953 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2954 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00002955
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002956 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2957 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2958
Ted Kremenek826a3452010-07-16 02:11:22 +00002959 // The remaining checks depend on the data arguments.
2960 if (HasVAListArg)
2961 return true;
2962
Ted Kremenek666a1972010-07-26 19:45:42 +00002963 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002964 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002965
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002966 // Check that the argument type matches the format specifier.
2967 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002968 if (!Ex)
2969 return true;
2970
Hans Wennborg58e1e542012-08-07 08:59:46 +00002971 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2972 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002973 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002974 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002975 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002976
2977 if (success) {
2978 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002979 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002980 llvm::raw_svector_ostream os(buf);
2981 fixedFS.toString(os);
2982
2983 EmitFormatDiagnostic(
2984 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002985 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002986 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002987 Ex->getLocStart(),
2988 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002989 getSpecifierRange(startSpecifier, specifierLen),
2990 FixItHint::CreateReplacement(
2991 getSpecifierRange(startSpecifier, specifierLen),
2992 os.str()));
2993 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002994 EmitFormatDiagnostic(
2995 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002996 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002997 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002998 Ex->getLocStart(),
2999 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003000 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003001 }
3002 }
3003
Ted Kremenek826a3452010-07-16 02:11:22 +00003004 return true;
3005}
3006
3007void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003008 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003009 Expr **Args, unsigned NumArgs,
3010 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003011 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003012 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003013
Ted Kremeneke0e53132010-01-28 23:39:18 +00003014 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003015 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003016 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003017 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003018 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3019 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003020 return;
3021 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003022
Ted Kremeneke0e53132010-01-28 23:39:18 +00003023 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003024 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003025 const char *Str = StrRef.data();
3026 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003027 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003028
Ted Kremeneke0e53132010-01-28 23:39:18 +00003029 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003030 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003031 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003032 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003033 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3034 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003035 return;
3036 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003037
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003038 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003039 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003040 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003041 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003042 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003043
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003044 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003045 getLangOpts(),
3046 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003047 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003048 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003049 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003050 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003051 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003052
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003053 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003054 getLangOpts(),
3055 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003056 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003057 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003058}
3059
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003060//===--- CHECK: Standard memory functions ---------------------------------===//
3061
Douglas Gregor2a053a32011-05-03 20:05:22 +00003062/// \brief Determine whether the given type is a dynamic class type (e.g.,
3063/// whether it has a vtable).
3064static bool isDynamicClassType(QualType T) {
3065 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3066 if (CXXRecordDecl *Definition = Record->getDefinition())
3067 if (Definition->isDynamicClass())
3068 return true;
3069
3070 return false;
3071}
3072
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003073/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003074/// otherwise returns NULL.
3075static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003076 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003077 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3078 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3079 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003080
Chandler Carruth000d4282011-06-16 09:09:40 +00003081 return 0;
3082}
3083
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003084/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003085static QualType getSizeOfArgType(const Expr* E) {
3086 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3087 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3088 if (SizeOf->getKind() == clang::UETT_SizeOf)
3089 return SizeOf->getTypeOfArgument();
3090
3091 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003092}
3093
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003094/// \brief Check for dangerous or invalid arguments to memset().
3095///
Chandler Carruth929f0132011-06-03 06:23:57 +00003096/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003097/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3098/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003099///
3100/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003101void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003102 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003103 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003104 assert(BId != 0);
3105
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003106 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003107 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003108 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003109 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003110 return;
3111
Anna Zaks0a151a12012-01-17 00:37:07 +00003112 unsigned LastArg = (BId == Builtin::BImemset ||
3113 BId == Builtin::BIstrndup ? 1 : 2);
3114 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003115 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003116
3117 // We have special checking when the length is a sizeof expression.
3118 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3119 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3120 llvm::FoldingSetNodeID SizeOfArgID;
3121
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003122 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3123 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003124 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003125
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003126 QualType DestTy = Dest->getType();
3127 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3128 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003129
Chandler Carruth000d4282011-06-16 09:09:40 +00003130 // Never warn about void type pointers. This can be used to suppress
3131 // false positives.
3132 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003133 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003134
Chandler Carruth000d4282011-06-16 09:09:40 +00003135 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3136 // actually comparing the expressions for equality. Because computing the
3137 // expression IDs can be expensive, we only do this if the diagnostic is
3138 // enabled.
3139 if (SizeOfArg &&
3140 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3141 SizeOfArg->getExprLoc())) {
3142 // We only compute IDs for expressions if the warning is enabled, and
3143 // cache the sizeof arg's ID.
3144 if (SizeOfArgID == llvm::FoldingSetNodeID())
3145 SizeOfArg->Profile(SizeOfArgID, Context, true);
3146 llvm::FoldingSetNodeID DestID;
3147 Dest->Profile(DestID, Context, true);
3148 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003149 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3150 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003151 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003152 StringRef ReadableName = FnName->getName();
3153
Chandler Carruth000d4282011-06-16 09:09:40 +00003154 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003155 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003156 ActionIdx = 1; // If its an address-of operator, just remove it.
3157 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3158 ActionIdx = 2; // If the pointee's size is sizeof(char),
3159 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003160
3161 // If the function is defined as a builtin macro, do not show macro
3162 // expansion.
3163 SourceLocation SL = SizeOfArg->getExprLoc();
3164 SourceRange DSR = Dest->getSourceRange();
3165 SourceRange SSR = SizeOfArg->getSourceRange();
3166 SourceManager &SM = PP.getSourceManager();
3167
3168 if (SM.isMacroArgExpansion(SL)) {
3169 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3170 SL = SM.getSpellingLoc(SL);
3171 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3172 SM.getSpellingLoc(DSR.getEnd()));
3173 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3174 SM.getSpellingLoc(SSR.getEnd()));
3175 }
3176
Anna Zaks90c78322012-05-30 23:14:52 +00003177 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003178 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003179 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003180 << PointeeTy
3181 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003182 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003183 << SSR);
3184 DiagRuntimeBehavior(SL, SizeOfArg,
3185 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3186 << ActionIdx
3187 << SSR);
3188
Chandler Carruth000d4282011-06-16 09:09:40 +00003189 break;
3190 }
3191 }
3192
3193 // Also check for cases where the sizeof argument is the exact same
3194 // type as the memory argument, and where it points to a user-defined
3195 // record type.
3196 if (SizeOfArgTy != QualType()) {
3197 if (PointeeTy->isRecordType() &&
3198 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3199 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3200 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3201 << FnName << SizeOfArgTy << ArgIdx
3202 << PointeeTy << Dest->getSourceRange()
3203 << LenExpr->getSourceRange());
3204 break;
3205 }
Nico Webere4a1c642011-06-14 16:14:58 +00003206 }
3207
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003208 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003209 if (isDynamicClassType(PointeeTy)) {
3210
3211 unsigned OperationType = 0;
3212 // "overwritten" if we're warning about the destination for any call
3213 // but memcmp; otherwise a verb appropriate to the call.
3214 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3215 if (BId == Builtin::BImemcpy)
3216 OperationType = 1;
3217 else if(BId == Builtin::BImemmove)
3218 OperationType = 2;
3219 else if (BId == Builtin::BImemcmp)
3220 OperationType = 3;
3221 }
3222
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003223 DiagRuntimeBehavior(
3224 Dest->getExprLoc(), Dest,
3225 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003226 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003227 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003228 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003229 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003230 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3231 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003232 DiagRuntimeBehavior(
3233 Dest->getExprLoc(), Dest,
3234 PDiag(diag::warn_arc_object_memaccess)
3235 << ArgIdx << FnName << PointeeTy
3236 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003237 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003238 continue;
John McCallf85e1932011-06-15 23:02:42 +00003239
3240 DiagRuntimeBehavior(
3241 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003242 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003243 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3244 break;
3245 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003246 }
3247}
3248
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003249// A little helper routine: ignore addition and subtraction of integer literals.
3250// This intentionally does not ignore all integer constant expressions because
3251// we don't want to remove sizeof().
3252static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3253 Ex = Ex->IgnoreParenCasts();
3254
3255 for (;;) {
3256 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3257 if (!BO || !BO->isAdditiveOp())
3258 break;
3259
3260 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3261 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3262
3263 if (isa<IntegerLiteral>(RHS))
3264 Ex = LHS;
3265 else if (isa<IntegerLiteral>(LHS))
3266 Ex = RHS;
3267 else
3268 break;
3269 }
3270
3271 return Ex;
3272}
3273
Anna Zaks0f38ace2012-08-08 21:42:23 +00003274static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3275 ASTContext &Context) {
3276 // Only handle constant-sized or VLAs, but not flexible members.
3277 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3278 // Only issue the FIXIT for arrays of size > 1.
3279 if (CAT->getSize().getSExtValue() <= 1)
3280 return false;
3281 } else if (!Ty->isVariableArrayType()) {
3282 return false;
3283 }
3284 return true;
3285}
3286
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003287// Warn if the user has made the 'size' argument to strlcpy or strlcat
3288// be the size of the source, instead of the destination.
3289void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3290 IdentifierInfo *FnName) {
3291
3292 // Don't crash if the user has the wrong number of arguments
3293 if (Call->getNumArgs() != 3)
3294 return;
3295
3296 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3297 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3298 const Expr *CompareWithSrc = NULL;
3299
3300 // Look for 'strlcpy(dst, x, sizeof(x))'
3301 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3302 CompareWithSrc = Ex;
3303 else {
3304 // Look for 'strlcpy(dst, x, strlen(x))'
3305 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003306 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003307 && SizeCall->getNumArgs() == 1)
3308 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3309 }
3310 }
3311
3312 if (!CompareWithSrc)
3313 return;
3314
3315 // Determine if the argument to sizeof/strlen is equal to the source
3316 // argument. In principle there's all kinds of things you could do
3317 // here, for instance creating an == expression and evaluating it with
3318 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3319 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3320 if (!SrcArgDRE)
3321 return;
3322
3323 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3324 if (!CompareWithSrcDRE ||
3325 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3326 return;
3327
3328 const Expr *OriginalSizeArg = Call->getArg(2);
3329 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3330 << OriginalSizeArg->getSourceRange() << FnName;
3331
3332 // Output a FIXIT hint if the destination is an array (rather than a
3333 // pointer to an array). This could be enhanced to handle some
3334 // pointers if we know the actual size, like if DstArg is 'array+2'
3335 // we could say 'sizeof(array)-2'.
3336 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003337 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003338 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003339
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003340 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003341 llvm::raw_svector_ostream OS(sizeString);
3342 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003343 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003344 OS << ")";
3345
3346 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3347 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3348 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003349}
3350
Anna Zaksc36bedc2012-02-01 19:08:57 +00003351/// Check if two expressions refer to the same declaration.
3352static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3353 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3354 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3355 return D1->getDecl() == D2->getDecl();
3356 return false;
3357}
3358
3359static const Expr *getStrlenExprArg(const Expr *E) {
3360 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3361 const FunctionDecl *FD = CE->getDirectCallee();
3362 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3363 return 0;
3364 return CE->getArg(0)->IgnoreParenCasts();
3365 }
3366 return 0;
3367}
3368
3369// Warn on anti-patterns as the 'size' argument to strncat.
3370// The correct size argument should look like following:
3371// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3372void Sema::CheckStrncatArguments(const CallExpr *CE,
3373 IdentifierInfo *FnName) {
3374 // Don't crash if the user has the wrong number of arguments.
3375 if (CE->getNumArgs() < 3)
3376 return;
3377 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3378 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3379 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3380
3381 // Identify common expressions, which are wrongly used as the size argument
3382 // to strncat and may lead to buffer overflows.
3383 unsigned PatternType = 0;
3384 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3385 // - sizeof(dst)
3386 if (referToTheSameDecl(SizeOfArg, DstArg))
3387 PatternType = 1;
3388 // - sizeof(src)
3389 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3390 PatternType = 2;
3391 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3392 if (BE->getOpcode() == BO_Sub) {
3393 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3394 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3395 // - sizeof(dst) - strlen(dst)
3396 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3397 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3398 PatternType = 1;
3399 // - sizeof(src) - (anything)
3400 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3401 PatternType = 2;
3402 }
3403 }
3404
3405 if (PatternType == 0)
3406 return;
3407
Anna Zaksafdb0412012-02-03 01:27:37 +00003408 // Generate the diagnostic.
3409 SourceLocation SL = LenArg->getLocStart();
3410 SourceRange SR = LenArg->getSourceRange();
3411 SourceManager &SM = PP.getSourceManager();
3412
3413 // If the function is defined as a builtin macro, do not show macro expansion.
3414 if (SM.isMacroArgExpansion(SL)) {
3415 SL = SM.getSpellingLoc(SL);
3416 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3417 SM.getSpellingLoc(SR.getEnd()));
3418 }
3419
Anna Zaks0f38ace2012-08-08 21:42:23 +00003420 // Check if the destination is an array (rather than a pointer to an array).
3421 QualType DstTy = DstArg->getType();
3422 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3423 Context);
3424 if (!isKnownSizeArray) {
3425 if (PatternType == 1)
3426 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3427 else
3428 Diag(SL, diag::warn_strncat_src_size) << SR;
3429 return;
3430 }
3431
Anna Zaksc36bedc2012-02-01 19:08:57 +00003432 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003433 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003434 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003435 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003436
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003437 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003438 llvm::raw_svector_ostream OS(sizeString);
3439 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003440 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003441 OS << ") - ";
3442 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003443 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003444 OS << ") - 1";
3445
Anna Zaksafdb0412012-02-03 01:27:37 +00003446 Diag(SL, diag::note_strncat_wrong_size)
3447 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003448}
3449
Ted Kremenek06de2762007-08-17 16:46:58 +00003450//===--- CHECK: Return Address of Stack Variable --------------------------===//
3451
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003452static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3453 Decl *ParentDecl);
3454static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3455 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003456
3457/// CheckReturnStackAddr - Check if a return statement returns the address
3458/// of a stack variable.
3459void
3460Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3461 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003463 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003464 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003465
3466 // Perform checking for returned stack addresses, local blocks,
3467 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003468 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003469 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003470 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003471 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003472 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003473 }
3474
3475 if (stackE == 0)
3476 return; // Nothing suspicious was found.
3477
3478 SourceLocation diagLoc;
3479 SourceRange diagRange;
3480 if (refVars.empty()) {
3481 diagLoc = stackE->getLocStart();
3482 diagRange = stackE->getSourceRange();
3483 } else {
3484 // We followed through a reference variable. 'stackE' contains the
3485 // problematic expression but we will warn at the return statement pointing
3486 // at the reference variable. We will later display the "trail" of
3487 // reference variables using notes.
3488 diagLoc = refVars[0]->getLocStart();
3489 diagRange = refVars[0]->getSourceRange();
3490 }
3491
3492 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3493 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3494 : diag::warn_ret_stack_addr)
3495 << DR->getDecl()->getDeclName() << diagRange;
3496 } else if (isa<BlockExpr>(stackE)) { // local block.
3497 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3498 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3499 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3500 } else { // local temporary.
3501 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3502 : diag::warn_ret_local_temp_addr)
3503 << diagRange;
3504 }
3505
3506 // Display the "trail" of reference variables that we followed until we
3507 // found the problematic expression using notes.
3508 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3509 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3510 // If this var binds to another reference var, show the range of the next
3511 // var, otherwise the var binds to the problematic expression, in which case
3512 // show the range of the expression.
3513 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3514 : stackE->getSourceRange();
3515 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3516 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003517 }
3518}
3519
3520/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3521/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003522/// to a location on the stack, a local block, an address of a label, or a
3523/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003524/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003525/// encounter a subexpression that (1) clearly does not lead to one of the
3526/// above problematic expressions (2) is something we cannot determine leads to
3527/// a problematic expression based on such local checking.
3528///
3529/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3530/// the expression that they point to. Such variables are added to the
3531/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003532///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003533/// EvalAddr processes expressions that are pointers that are used as
3534/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003535/// At the base case of the recursion is a check for the above problematic
3536/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003537///
3538/// This implementation handles:
3539///
3540/// * pointer-to-pointer casts
3541/// * implicit conversions from array references to pointers
3542/// * taking the address of fields
3543/// * arbitrary interplay between "&" and "*" operators
3544/// * pointer arithmetic from an address of a stack variable
3545/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003546static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3547 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003548 if (E->isTypeDependent())
3549 return NULL;
3550
Ted Kremenek06de2762007-08-17 16:46:58 +00003551 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003552 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003553 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003554 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003555 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Peter Collingbournef111d932011-04-15 00:35:48 +00003557 E = E->IgnoreParens();
3558
Ted Kremenek06de2762007-08-17 16:46:58 +00003559 // Our "symbolic interpreter" is just a dispatch off the currently
3560 // viewed AST node. We then recursively traverse the AST by calling
3561 // EvalAddr and EvalVal appropriately.
3562 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003563 case Stmt::DeclRefExprClass: {
3564 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3565
3566 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3567 // If this is a reference variable, follow through to the expression that
3568 // it points to.
3569 if (V->hasLocalStorage() &&
3570 V->getType()->isReferenceType() && V->hasInit()) {
3571 // Add the reference variable to the "trail".
3572 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003573 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003574 }
3575
3576 return NULL;
3577 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003578
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003579 case Stmt::UnaryOperatorClass: {
3580 // The only unary operator that make sense to handle here
3581 // is AddrOf. All others don't make sense as pointers.
3582 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003583
John McCall2de56d12010-08-25 11:45:40 +00003584 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003585 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003586 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003587 return NULL;
3588 }
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003590 case Stmt::BinaryOperatorClass: {
3591 // Handle pointer arithmetic. All other binary operators are not valid
3592 // in this context.
3593 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003594 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003595
John McCall2de56d12010-08-25 11:45:40 +00003596 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003597 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003599 Expr *Base = B->getLHS();
3600
3601 // Determine which argument is the real pointer base. It could be
3602 // the RHS argument instead of the LHS.
3603 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003605 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003606 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003607 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003608
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003609 // For conditional operators we need to see if either the LHS or RHS are
3610 // valid DeclRefExpr*s. If one of them is valid, we return it.
3611 case Stmt::ConditionalOperatorClass: {
3612 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003614 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003615 if (Expr *lhsExpr = C->getLHS()) {
3616 // In C++, we can have a throw-expression, which has 'void' type.
3617 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003618 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003619 return LHS;
3620 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003621
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003622 // In C++, we can have a throw-expression, which has 'void' type.
3623 if (C->getRHS()->getType()->isVoidType())
3624 return NULL;
3625
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003626 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003627 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003628
3629 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003630 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003631 return E; // local block.
3632 return NULL;
3633
3634 case Stmt::AddrLabelExprClass:
3635 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003636
John McCall80ee6e82011-11-10 05:35:25 +00003637 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003638 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3639 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003640
Ted Kremenek54b52742008-08-07 00:49:01 +00003641 // For casts, we need to handle conversions from arrays to
3642 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003643 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003644 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003645 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003646 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003647 case Stmt::CXXStaticCastExprClass:
3648 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003649 case Stmt::CXXConstCastExprClass:
3650 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003651 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3652 switch (cast<CastExpr>(E)->getCastKind()) {
3653 case CK_BitCast:
3654 case CK_LValueToRValue:
3655 case CK_NoOp:
3656 case CK_BaseToDerived:
3657 case CK_DerivedToBase:
3658 case CK_UncheckedDerivedToBase:
3659 case CK_Dynamic:
3660 case CK_CPointerToObjCPointerCast:
3661 case CK_BlockPointerToObjCPointerCast:
3662 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003663 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003664
3665 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003666 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003667
3668 default:
3669 return 0;
3670 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Douglas Gregor03e80032011-06-21 17:03:29 +00003673 case Stmt::MaterializeTemporaryExprClass:
3674 if (Expr *Result = EvalAddr(
3675 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003676 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003677 return Result;
3678
3679 return E;
3680
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003681 // Everything else: we simply don't reason about them.
3682 default:
3683 return NULL;
3684 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003685}
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Ted Kremenek06de2762007-08-17 16:46:58 +00003687
3688/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3689/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003690static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3691 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003692do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003693 // We should only be called for evaluating non-pointer expressions, or
3694 // expressions with a pointer type that are not used as references but instead
3695 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Ted Kremenek06de2762007-08-17 16:46:58 +00003697 // Our "symbolic interpreter" is just a dispatch off the currently
3698 // viewed AST node. We then recursively traverse the AST by calling
3699 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003700
3701 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003702 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003703 case Stmt::ImplicitCastExprClass: {
3704 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003705 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003706 E = IE->getSubExpr();
3707 continue;
3708 }
3709 return NULL;
3710 }
3711
John McCall80ee6e82011-11-10 05:35:25 +00003712 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003713 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003714
Douglas Gregora2813ce2009-10-23 18:54:35 +00003715 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003716 // When we hit a DeclRefExpr we are looking at code that refers to a
3717 // variable's name. If it's not a reference variable we check if it has
3718 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003719 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003721 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3722 // Check if it refers to itself, e.g. "int& i = i;".
3723 if (V == ParentDecl)
3724 return DR;
3725
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003726 if (V->hasLocalStorage()) {
3727 if (!V->getType()->isReferenceType())
3728 return DR;
3729
3730 // Reference variable, follow through to the expression that
3731 // it points to.
3732 if (V->hasInit()) {
3733 // Add the reference variable to the "trail".
3734 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003735 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003736 }
3737 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003738 }
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Ted Kremenek06de2762007-08-17 16:46:58 +00003740 return NULL;
3741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Ted Kremenek06de2762007-08-17 16:46:58 +00003743 case Stmt::UnaryOperatorClass: {
3744 // The only unary operator that make sense to handle here
3745 // is Deref. All others don't resolve to a "name." This includes
3746 // handling all sorts of rvalues passed to a unary operator.
3747 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003748
John McCall2de56d12010-08-25 11:45:40 +00003749 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003750 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003751
3752 return NULL;
3753 }
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Ted Kremenek06de2762007-08-17 16:46:58 +00003755 case Stmt::ArraySubscriptExprClass: {
3756 // Array subscripts are potential references to data on the stack. We
3757 // retrieve the DeclRefExpr* for the array variable if it indeed
3758 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003759 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Ted Kremenek06de2762007-08-17 16:46:58 +00003762 case Stmt::ConditionalOperatorClass: {
3763 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003764 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003765 ConditionalOperator *C = cast<ConditionalOperator>(E);
3766
Anders Carlsson39073232007-11-30 19:04:31 +00003767 // Handle the GNU extension for missing LHS.
3768 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003769 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003770 return LHS;
3771
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003772 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003773 }
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Ted Kremenek06de2762007-08-17 16:46:58 +00003775 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003776 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003777 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Ted Kremenek06de2762007-08-17 16:46:58 +00003779 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003780 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003781 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003782
3783 // Check whether the member type is itself a reference, in which case
3784 // we're not going to refer to the member, but to what the member refers to.
3785 if (M->getMemberDecl()->getType()->isReferenceType())
3786 return NULL;
3787
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003788 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Douglas Gregor03e80032011-06-21 17:03:29 +00003791 case Stmt::MaterializeTemporaryExprClass:
3792 if (Expr *Result = EvalVal(
3793 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003794 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003795 return Result;
3796
3797 return E;
3798
Ted Kremenek06de2762007-08-17 16:46:58 +00003799 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003800 // Check that we don't return or take the address of a reference to a
3801 // temporary. This is only useful in C++.
3802 if (!E->isTypeDependent() && E->isRValue())
3803 return E;
3804
3805 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003806 return NULL;
3807 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003808} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003809}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003810
3811//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3812
3813/// Check for comparisons of floating point operands using != and ==.
3814/// Issue a warning if these are no self-comparisons, as they are not likely
3815/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003816void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003817 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3818 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003819
3820 // Special case: check for x == x (which is OK).
3821 // Do not emit warnings for such cases.
3822 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3823 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3824 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003825 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003826
3827
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003828 // Special case: check for comparisons against literals that can be exactly
3829 // represented by APFloat. In such cases, do not emit a warning. This
3830 // is a heuristic: often comparison against such literals are used to
3831 // detect if a value in a variable has not changed. This clearly can
3832 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003833 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3834 if (FLL->isExact())
3835 return;
3836 } else
3837 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3838 if (FLR->isExact())
3839 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003841 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003842 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3843 if (CL->isBuiltinCall())
3844 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003845
David Blaikie980343b2012-07-16 20:47:22 +00003846 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3847 if (CR->isBuiltinCall())
3848 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003850 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003851 Diag(Loc, diag::warn_floatingpoint_eq)
3852 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003853}
John McCallba26e582010-01-04 23:21:16 +00003854
John McCallf2370c92010-01-06 05:24:50 +00003855//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3856//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003857
John McCallf2370c92010-01-06 05:24:50 +00003858namespace {
John McCallba26e582010-01-04 23:21:16 +00003859
John McCallf2370c92010-01-06 05:24:50 +00003860/// Structure recording the 'active' range of an integer-valued
3861/// expression.
3862struct IntRange {
3863 /// The number of bits active in the int.
3864 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003865
John McCallf2370c92010-01-06 05:24:50 +00003866 /// True if the int is known not to have negative values.
3867 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003868
John McCallf2370c92010-01-06 05:24:50 +00003869 IntRange(unsigned Width, bool NonNegative)
3870 : Width(Width), NonNegative(NonNegative)
3871 {}
John McCallba26e582010-01-04 23:21:16 +00003872
John McCall1844a6e2010-11-10 23:38:19 +00003873 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003874 static IntRange forBoolType() {
3875 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003876 }
3877
John McCall1844a6e2010-11-10 23:38:19 +00003878 /// Returns the range of an opaque value of the given integral type.
3879 static IntRange forValueOfType(ASTContext &C, QualType T) {
3880 return forValueOfCanonicalType(C,
3881 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003882 }
3883
John McCall1844a6e2010-11-10 23:38:19 +00003884 /// Returns the range of an opaque value of a canonical integral type.
3885 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003886 assert(T->isCanonicalUnqualified());
3887
3888 if (const VectorType *VT = dyn_cast<VectorType>(T))
3889 T = VT->getElementType().getTypePtr();
3890 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3891 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003892
John McCall091f23f2010-11-09 22:22:12 +00003893 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003894 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3895 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003896 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003897 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3898
John McCall323ed742010-05-06 08:58:33 +00003899 unsigned NumPositive = Enum->getNumPositiveBits();
3900 unsigned NumNegative = Enum->getNumNegativeBits();
3901
3902 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3903 }
John McCallf2370c92010-01-06 05:24:50 +00003904
3905 const BuiltinType *BT = cast<BuiltinType>(T);
3906 assert(BT->isInteger());
3907
3908 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3909 }
3910
John McCall1844a6e2010-11-10 23:38:19 +00003911 /// Returns the "target" range of a canonical integral type, i.e.
3912 /// the range of values expressible in the type.
3913 ///
3914 /// This matches forValueOfCanonicalType except that enums have the
3915 /// full range of their type, not the range of their enumerators.
3916 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3917 assert(T->isCanonicalUnqualified());
3918
3919 if (const VectorType *VT = dyn_cast<VectorType>(T))
3920 T = VT->getElementType().getTypePtr();
3921 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3922 T = CT->getElementType().getTypePtr();
3923 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003924 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003925
3926 const BuiltinType *BT = cast<BuiltinType>(T);
3927 assert(BT->isInteger());
3928
3929 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3930 }
3931
3932 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003933 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003934 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003935 L.NonNegative && R.NonNegative);
3936 }
3937
John McCall1844a6e2010-11-10 23:38:19 +00003938 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003939 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003940 return IntRange(std::min(L.Width, R.Width),
3941 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003942 }
3943};
3944
Ted Kremenek0692a192012-01-31 05:37:37 +00003945static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3946 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003947 if (value.isSigned() && value.isNegative())
3948 return IntRange(value.getMinSignedBits(), false);
3949
3950 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003951 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003952
3953 // isNonNegative() just checks the sign bit without considering
3954 // signedness.
3955 return IntRange(value.getActiveBits(), true);
3956}
3957
Ted Kremenek0692a192012-01-31 05:37:37 +00003958static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3959 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003960 if (result.isInt())
3961 return GetValueRange(C, result.getInt(), MaxWidth);
3962
3963 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003964 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3965 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3966 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3967 R = IntRange::join(R, El);
3968 }
John McCallf2370c92010-01-06 05:24:50 +00003969 return R;
3970 }
3971
3972 if (result.isComplexInt()) {
3973 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3974 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3975 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003976 }
3977
3978 // This can happen with lossless casts to intptr_t of "based" lvalues.
3979 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003980 // FIXME: The only reason we need to pass the type in here is to get
3981 // the sign right on this one case. It would be nice if APValue
3982 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003983 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003984 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003985}
John McCallf2370c92010-01-06 05:24:50 +00003986
3987/// Pseudo-evaluate the given integer expression, estimating the
3988/// range of values it might take.
3989///
3990/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003991static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003992 E = E->IgnoreParens();
3993
3994 // Try a full evaluation first.
3995 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003996 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003997 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003998
3999 // I think we only want to look through implicit casts here; if the
4000 // user has an explicit widening cast, we should treat the value as
4001 // being of the new, wider type.
4002 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004003 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004004 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4005
John McCall1844a6e2010-11-10 23:38:19 +00004006 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004007
John McCall2de56d12010-08-25 11:45:40 +00004008 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004009
John McCallf2370c92010-01-06 05:24:50 +00004010 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004011 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004012 return OutputTypeRange;
4013
4014 IntRange SubRange
4015 = GetExprRange(C, CE->getSubExpr(),
4016 std::min(MaxWidth, OutputTypeRange.Width));
4017
4018 // Bail out if the subexpr's range is as wide as the cast type.
4019 if (SubRange.Width >= OutputTypeRange.Width)
4020 return OutputTypeRange;
4021
4022 // Otherwise, we take the smaller width, and we're non-negative if
4023 // either the output type or the subexpr is.
4024 return IntRange(SubRange.Width,
4025 SubRange.NonNegative || OutputTypeRange.NonNegative);
4026 }
4027
4028 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4029 // If we can fold the condition, just take that operand.
4030 bool CondResult;
4031 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4032 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4033 : CO->getFalseExpr(),
4034 MaxWidth);
4035
4036 // Otherwise, conservatively merge.
4037 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4038 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4039 return IntRange::join(L, R);
4040 }
4041
4042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4043 switch (BO->getOpcode()) {
4044
4045 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004046 case BO_LAnd:
4047 case BO_LOr:
4048 case BO_LT:
4049 case BO_GT:
4050 case BO_LE:
4051 case BO_GE:
4052 case BO_EQ:
4053 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004054 return IntRange::forBoolType();
4055
John McCall862ff872011-07-13 06:35:24 +00004056 // The type of the assignments is the type of the LHS, so the RHS
4057 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004058 case BO_MulAssign:
4059 case BO_DivAssign:
4060 case BO_RemAssign:
4061 case BO_AddAssign:
4062 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004063 case BO_XorAssign:
4064 case BO_OrAssign:
4065 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004066 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004067
John McCall862ff872011-07-13 06:35:24 +00004068 // Simple assignments just pass through the RHS, which will have
4069 // been coerced to the LHS type.
4070 case BO_Assign:
4071 // TODO: bitfields?
4072 return GetExprRange(C, BO->getRHS(), MaxWidth);
4073
John McCallf2370c92010-01-06 05:24:50 +00004074 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004075 case BO_PtrMemD:
4076 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004077 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004078
John McCall60fad452010-01-06 22:07:33 +00004079 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004080 case BO_And:
4081 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004082 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4083 GetExprRange(C, BO->getRHS(), MaxWidth));
4084
John McCallf2370c92010-01-06 05:24:50 +00004085 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004086 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004087 // ...except that we want to treat '1 << (blah)' as logically
4088 // positive. It's an important idiom.
4089 if (IntegerLiteral *I
4090 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4091 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004092 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004093 return IntRange(R.Width, /*NonNegative*/ true);
4094 }
4095 }
4096 // fallthrough
4097
John McCall2de56d12010-08-25 11:45:40 +00004098 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004099 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004100
John McCall60fad452010-01-06 22:07:33 +00004101 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004102 case BO_Shr:
4103 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004104 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4105
4106 // If the shift amount is a positive constant, drop the width by
4107 // that much.
4108 llvm::APSInt shift;
4109 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4110 shift.isNonNegative()) {
4111 unsigned zext = shift.getZExtValue();
4112 if (zext >= L.Width)
4113 L.Width = (L.NonNegative ? 0 : 1);
4114 else
4115 L.Width -= zext;
4116 }
4117
4118 return L;
4119 }
4120
4121 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004122 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004123 return GetExprRange(C, BO->getRHS(), MaxWidth);
4124
John McCall60fad452010-01-06 22:07:33 +00004125 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004126 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004127 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004128 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004129 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004130
John McCall00fe7612011-07-14 22:39:48 +00004131 // The width of a division result is mostly determined by the size
4132 // of the LHS.
4133 case BO_Div: {
4134 // Don't 'pre-truncate' the operands.
4135 unsigned opWidth = C.getIntWidth(E->getType());
4136 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4137
4138 // If the divisor is constant, use that.
4139 llvm::APSInt divisor;
4140 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4141 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4142 if (log2 >= L.Width)
4143 L.Width = (L.NonNegative ? 0 : 1);
4144 else
4145 L.Width = std::min(L.Width - log2, MaxWidth);
4146 return L;
4147 }
4148
4149 // Otherwise, just use the LHS's width.
4150 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4151 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4152 }
4153
4154 // The result of a remainder can't be larger than the result of
4155 // either side.
4156 case BO_Rem: {
4157 // Don't 'pre-truncate' the operands.
4158 unsigned opWidth = C.getIntWidth(E->getType());
4159 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4160 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4161
4162 IntRange meet = IntRange::meet(L, R);
4163 meet.Width = std::min(meet.Width, MaxWidth);
4164 return meet;
4165 }
4166
4167 // The default behavior is okay for these.
4168 case BO_Mul:
4169 case BO_Add:
4170 case BO_Xor:
4171 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004172 break;
4173 }
4174
John McCall00fe7612011-07-14 22:39:48 +00004175 // The default case is to treat the operation as if it were closed
4176 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004177 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4178 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4179 return IntRange::join(L, R);
4180 }
4181
4182 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4183 switch (UO->getOpcode()) {
4184 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004185 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004186 return IntRange::forBoolType();
4187
4188 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004189 case UO_Deref:
4190 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004191 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004192
4193 default:
4194 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4195 }
4196 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004197
4198 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004199 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004200 }
John McCallf2370c92010-01-06 05:24:50 +00004201
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004202 if (FieldDecl *BitField = E->getBitField())
4203 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004204 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004205
John McCall1844a6e2010-11-10 23:38:19 +00004206 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004207}
John McCall51313c32010-01-04 23:31:57 +00004208
Ted Kremenek0692a192012-01-31 05:37:37 +00004209static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004210 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4211}
4212
John McCall51313c32010-01-04 23:31:57 +00004213/// Checks whether the given value, which currently has the given
4214/// source semantics, has the same value when coerced through the
4215/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004216static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4217 const llvm::fltSemantics &Src,
4218 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004219 llvm::APFloat truncated = value;
4220
4221 bool ignored;
4222 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4223 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4224
4225 return truncated.bitwiseIsEqual(value);
4226}
4227
4228/// Checks whether the given value, which currently has the given
4229/// source semantics, has the same value when coerced through the
4230/// target semantics.
4231///
4232/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004233static bool IsSameFloatAfterCast(const APValue &value,
4234 const llvm::fltSemantics &Src,
4235 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004236 if (value.isFloat())
4237 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4238
4239 if (value.isVector()) {
4240 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4241 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4242 return false;
4243 return true;
4244 }
4245
4246 assert(value.isComplexFloat());
4247 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4248 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4249}
4250
Ted Kremenek0692a192012-01-31 05:37:37 +00004251static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004252
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004253static bool IsZero(Sema &S, Expr *E) {
4254 // Suppress cases where we are comparing against an enum constant.
4255 if (const DeclRefExpr *DR =
4256 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4257 if (isa<EnumConstantDecl>(DR->getDecl()))
4258 return false;
4259
4260 // Suppress cases where the '0' value is expanded from a macro.
4261 if (E->getLocStart().isMacroID())
4262 return false;
4263
John McCall323ed742010-05-06 08:58:33 +00004264 llvm::APSInt Value;
4265 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4266}
4267
John McCall372e1032010-10-06 00:25:24 +00004268static bool HasEnumType(Expr *E) {
4269 // Strip off implicit integral promotions.
4270 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004271 if (ICE->getCastKind() != CK_IntegralCast &&
4272 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004273 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004274 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004275 }
4276
4277 return E->getType()->isEnumeralType();
4278}
4279
Ted Kremenek0692a192012-01-31 05:37:37 +00004280static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004281 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004282 if (E->isValueDependent())
4283 return;
4284
John McCall2de56d12010-08-25 11:45:40 +00004285 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004286 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004287 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004288 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004289 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004290 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004291 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004292 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004293 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004294 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004295 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004297 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004298 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004299 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004300 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4301 }
4302}
4303
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004304static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004305 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004306 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004307 bool RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004308 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004309 QualType OtherT = Other->getType();
4310 QualType ConstantT = Constant->getType();
4311 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004312 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004313 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004314 && "comparison with non-integer type");
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004315 // FIXME. handle cases for signedness to catch (signed char)N == 200
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004316 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004317 IntRange LitRange = GetValueRange(S.Context, Value, Value.getBitWidth());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004318 if (OtherRange.Width >= LitRange.Width)
4319 return;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004320 bool IsTrue = true;
4321 if (op == BO_EQ)
4322 IsTrue = false;
4323 else if (op == BO_NE)
4324 IsTrue = true;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004325 else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004326 if (op == BO_GT || op == BO_GE)
4327 IsTrue = !LitRange.NonNegative;
4328 else // op == BO_LT || op == BO_LE
4329 IsTrue = LitRange.NonNegative;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004330 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004331 if (op == BO_LT || op == BO_LE)
4332 IsTrue = !LitRange.NonNegative;
4333 else // op == BO_GT || op == BO_GE
4334 IsTrue = LitRange.NonNegative;
4335 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004336 SmallString<16> PrettySourceValue(Value.toString(10));
4337 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4338 << PrettySourceValue << OtherT << IsTrue
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004339 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4340}
4341
John McCall323ed742010-05-06 08:58:33 +00004342/// Analyze the operands of the given comparison. Implements the
4343/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004344static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004345 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4346 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004347}
John McCall51313c32010-01-04 23:31:57 +00004348
John McCallba26e582010-01-04 23:21:16 +00004349/// \brief Implements -Wsign-compare.
4350///
Richard Trieudd225092011-09-15 21:56:47 +00004351/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004352static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004353 // The type the comparison is being performed in.
4354 QualType T = E->getLHS()->getType();
4355 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4356 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004357 if (E->isValueDependent())
4358 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004359
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004360 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4361 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004362
4363 bool IsComparisonConstant = false;
4364
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004365 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004366 // of 'true' or 'false'.
4367 if (T->isIntegralType(S.Context)) {
4368 llvm::APSInt RHSValue;
4369 bool IsRHSIntegralLiteral =
4370 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4371 llvm::APSInt LHSValue;
4372 bool IsLHSIntegralLiteral =
4373 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4374 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4375 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4376 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4377 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4378 else
4379 IsComparisonConstant =
4380 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004381 } else if (!T->hasUnsignedIntegerRepresentation())
4382 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004383
John McCall323ed742010-05-06 08:58:33 +00004384 // We don't do anything special if this isn't an unsigned integral
4385 // comparison: we're only interested in integral comparisons, and
4386 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004387 //
4388 // We also don't care about value-dependent expressions or expressions
4389 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004390 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004391 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004392
John McCall323ed742010-05-06 08:58:33 +00004393 // Check to see if one of the (unmodified) operands is of different
4394 // signedness.
4395 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004396 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4397 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004398 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004399 signedOperand = LHS;
4400 unsignedOperand = RHS;
4401 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4402 signedOperand = RHS;
4403 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004404 } else {
John McCall323ed742010-05-06 08:58:33 +00004405 CheckTrivialUnsignedComparison(S, E);
4406 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004407 }
4408
John McCall323ed742010-05-06 08:58:33 +00004409 // Otherwise, calculate the effective range of the signed operand.
4410 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004411
John McCall323ed742010-05-06 08:58:33 +00004412 // Go ahead and analyze implicit conversions in the operands. Note
4413 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004414 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4415 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004416
John McCall323ed742010-05-06 08:58:33 +00004417 // If the signed range is non-negative, -Wsign-compare won't fire,
4418 // but we should still check for comparisons which are always true
4419 // or false.
4420 if (signedRange.NonNegative)
4421 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004422
4423 // For (in)equality comparisons, if the unsigned operand is a
4424 // constant which cannot collide with a overflowed signed operand,
4425 // then reinterpreting the signed operand as unsigned will not
4426 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004427 if (E->isEqualityOp()) {
4428 unsigned comparisonWidth = S.Context.getIntWidth(T);
4429 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004430
John McCall323ed742010-05-06 08:58:33 +00004431 // We should never be unable to prove that the unsigned operand is
4432 // non-negative.
4433 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4434
4435 if (unsignedRange.Width < comparisonWidth)
4436 return;
4437 }
4438
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004439 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4440 S.PDiag(diag::warn_mixed_sign_comparison)
4441 << LHS->getType() << RHS->getType()
4442 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004443}
4444
John McCall15d7d122010-11-11 03:21:53 +00004445/// Analyzes an attempt to assign the given value to a bitfield.
4446///
4447/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004448static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4449 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004450 assert(Bitfield->isBitField());
4451 if (Bitfield->isInvalidDecl())
4452 return false;
4453
John McCall91b60142010-11-11 05:33:51 +00004454 // White-list bool bitfields.
4455 if (Bitfield->getType()->isBooleanType())
4456 return false;
4457
Douglas Gregor46ff3032011-02-04 13:09:01 +00004458 // Ignore value- or type-dependent expressions.
4459 if (Bitfield->getBitWidth()->isValueDependent() ||
4460 Bitfield->getBitWidth()->isTypeDependent() ||
4461 Init->isValueDependent() ||
4462 Init->isTypeDependent())
4463 return false;
4464
John McCall15d7d122010-11-11 03:21:53 +00004465 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4466
Richard Smith80d4b552011-12-28 19:48:30 +00004467 llvm::APSInt Value;
4468 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004469 return false;
4470
John McCall15d7d122010-11-11 03:21:53 +00004471 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004472 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004473
4474 if (OriginalWidth <= FieldWidth)
4475 return false;
4476
Eli Friedman3a643af2012-01-26 23:11:39 +00004477 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004478 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004479 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004480
Eli Friedman3a643af2012-01-26 23:11:39 +00004481 // Check whether the stored value is equal to the original value.
4482 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004483 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004484 return false;
4485
Eli Friedman3a643af2012-01-26 23:11:39 +00004486 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004487 // therefore don't strictly fit into a signed bitfield of width 1.
4488 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004489 return false;
4490
John McCall15d7d122010-11-11 03:21:53 +00004491 std::string PrettyValue = Value.toString(10);
4492 std::string PrettyTrunc = TruncatedValue.toString(10);
4493
4494 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4495 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4496 << Init->getSourceRange();
4497
4498 return true;
4499}
4500
John McCallbeb22aa2010-11-09 23:24:47 +00004501/// Analyze the given simple or compound assignment for warning-worthy
4502/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004503static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004504 // Just recurse on the LHS.
4505 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4506
4507 // We want to recurse on the RHS as normal unless we're assigning to
4508 // a bitfield.
4509 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004510 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4511 E->getOperatorLoc())) {
4512 // Recurse, ignoring any implicit conversions on the RHS.
4513 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4514 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004515 }
4516 }
4517
4518 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4519}
4520
John McCall51313c32010-01-04 23:31:57 +00004521/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004522static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004523 SourceLocation CContext, unsigned diag,
4524 bool pruneControlFlow = false) {
4525 if (pruneControlFlow) {
4526 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4527 S.PDiag(diag)
4528 << SourceType << T << E->getSourceRange()
4529 << SourceRange(CContext));
4530 return;
4531 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004532 S.Diag(E->getExprLoc(), diag)
4533 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4534}
4535
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004536/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004537static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004538 SourceLocation CContext, unsigned diag,
4539 bool pruneControlFlow = false) {
4540 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004541}
4542
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004543/// Diagnose an implicit cast from a literal expression. Does not warn when the
4544/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004545void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4546 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004547 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004548 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004549 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004550 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4551 T->hasUnsignedIntegerRepresentation());
4552 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004553 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004554 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004555 return;
4556
David Blaikiebe0ee872012-05-15 16:56:36 +00004557 SmallString<16> PrettySourceValue;
4558 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004559 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004560 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4561 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4562 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004563 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004564
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004565 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004566 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4567 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004568}
4569
John McCall091f23f2010-11-09 22:22:12 +00004570std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4571 if (!Range.Width) return "0";
4572
4573 llvm::APSInt ValueInRange = Value;
4574 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004575 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004576 return ValueInRange.toString(10);
4577}
4578
Hans Wennborg88617a22012-08-28 15:44:30 +00004579static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4580 if (!isa<ImplicitCastExpr>(Ex))
4581 return false;
4582
4583 Expr *InnerE = Ex->IgnoreParenImpCasts();
4584 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4585 const Type *Source =
4586 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4587 if (Target->isDependentType())
4588 return false;
4589
4590 const BuiltinType *FloatCandidateBT =
4591 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4592 const Type *BoolCandidateType = ToBool ? Target : Source;
4593
4594 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4595 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4596}
4597
4598void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4599 SourceLocation CC) {
4600 unsigned NumArgs = TheCall->getNumArgs();
4601 for (unsigned i = 0; i < NumArgs; ++i) {
4602 Expr *CurrA = TheCall->getArg(i);
4603 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4604 continue;
4605
4606 bool IsSwapped = ((i > 0) &&
4607 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4608 IsSwapped |= ((i < (NumArgs - 1)) &&
4609 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4610 if (IsSwapped) {
4611 // Warn on this floating-point to bool conversion.
4612 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4613 CurrA->getType(), CC,
4614 diag::warn_impcast_floating_point_to_bool);
4615 }
4616 }
4617}
4618
John McCall323ed742010-05-06 08:58:33 +00004619void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004620 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004621 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004622
John McCall323ed742010-05-06 08:58:33 +00004623 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4624 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4625 if (Source == Target) return;
4626 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004627
Chandler Carruth108f7562011-07-26 05:40:03 +00004628 // If the conversion context location is invalid don't complain. We also
4629 // don't want to emit a warning if the issue occurs from the expansion of
4630 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4631 // delay this check as long as possible. Once we detect we are in that
4632 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004633 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004634 return;
4635
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004636 // Diagnose implicit casts to bool.
4637 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4638 if (isa<StringLiteral>(E))
4639 // Warn on string literal to bool. Checks for string literals in logical
4640 // expressions, for instances, assert(0 && "error here"), is prevented
4641 // by a check in AnalyzeImplicitConversions().
4642 return DiagnoseImpCast(S, E, T, CC,
4643 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004644 if (Source->isFunctionType()) {
4645 // Warn on function to bool. Checks free functions and static member
4646 // functions. Weakly imported functions are excluded from the check,
4647 // since it's common to test their value to check whether the linker
4648 // found a definition for them.
4649 ValueDecl *D = 0;
4650 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4651 D = R->getDecl();
4652 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4653 D = M->getMemberDecl();
4654 }
4655
4656 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004657 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4658 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4659 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004660 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4661 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4662 QualType ReturnType;
4663 UnresolvedSet<4> NonTemplateOverloads;
4664 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4665 if (!ReturnType.isNull()
4666 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4667 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4668 << FixItHint::CreateInsertion(
4669 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004670 return;
4671 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004672 }
4673 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004674 }
John McCall51313c32010-01-04 23:31:57 +00004675
4676 // Strip vector types.
4677 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004678 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004679 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004680 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004681 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004682 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004683
4684 // If the vector cast is cast between two vectors of the same size, it is
4685 // a bitcast, not a conversion.
4686 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4687 return;
John McCall51313c32010-01-04 23:31:57 +00004688
4689 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4690 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4691 }
4692
4693 // Strip complex types.
4694 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004695 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004696 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004697 return;
4698
John McCallb4eb64d2010-10-08 02:01:28 +00004699 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004700 }
John McCall51313c32010-01-04 23:31:57 +00004701
4702 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4703 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4704 }
4705
4706 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4707 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4708
4709 // If the source is floating point...
4710 if (SourceBT && SourceBT->isFloatingPoint()) {
4711 // ...and the target is floating point...
4712 if (TargetBT && TargetBT->isFloatingPoint()) {
4713 // ...then warn if we're dropping FP rank.
4714
4715 // Builtin FP kinds are ordered by increasing FP rank.
4716 if (SourceBT->getKind() > TargetBT->getKind()) {
4717 // Don't warn about float constants that are precisely
4718 // representable in the target type.
4719 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004720 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004721 // Value might be a float, a float vector, or a float complex.
4722 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004723 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4724 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004725 return;
4726 }
4727
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004728 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004729 return;
4730
John McCallb4eb64d2010-10-08 02:01:28 +00004731 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004732 }
4733 return;
4734 }
4735
Ted Kremenekef9ff882011-03-10 20:03:42 +00004736 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004737 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004738 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004739 return;
4740
Chandler Carrutha5b93322011-02-17 11:05:49 +00004741 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004742 // We also want to warn on, e.g., "int i = -1.234"
4743 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4744 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4745 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4746
Chandler Carruthf65076e2011-04-10 08:36:24 +00004747 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4748 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004749 } else {
4750 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4751 }
4752 }
John McCall51313c32010-01-04 23:31:57 +00004753
Hans Wennborg88617a22012-08-28 15:44:30 +00004754 // If the target is bool, warn if expr is a function or method call.
4755 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4756 isa<CallExpr>(E)) {
4757 // Check last argument of function call to see if it is an
4758 // implicit cast from a type matching the type the result
4759 // is being cast to.
4760 CallExpr *CEx = cast<CallExpr>(E);
4761 unsigned NumArgs = CEx->getNumArgs();
4762 if (NumArgs > 0) {
4763 Expr *LastA = CEx->getArg(NumArgs - 1);
4764 Expr *InnerE = LastA->IgnoreParenImpCasts();
4765 const Type *InnerType =
4766 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4767 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4768 // Warn on this floating-point to bool conversion
4769 DiagnoseImpCast(S, E, T, CC,
4770 diag::warn_impcast_floating_point_to_bool);
4771 }
4772 }
4773 }
John McCall51313c32010-01-04 23:31:57 +00004774 return;
4775 }
4776
Richard Trieu1838ca52011-05-29 19:59:02 +00004777 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004778 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004779 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004780 SourceLocation Loc = E->getSourceRange().getBegin();
4781 if (Loc.isMacroID())
4782 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004783 if (!Loc.isMacroID() || CC.isMacroID())
4784 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4785 << T << clang::SourceRange(CC)
4786 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004787 }
4788
David Blaikieb26331b2012-06-19 21:19:06 +00004789 if (!Source->isIntegerType() || !Target->isIntegerType())
4790 return;
4791
David Blaikiebe0ee872012-05-15 16:56:36 +00004792 // TODO: remove this early return once the false positives for constant->bool
4793 // in templates, macros, etc, are reduced or removed.
4794 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4795 return;
4796
John McCall323ed742010-05-06 08:58:33 +00004797 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004798 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004799
4800 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004801 // If the source is a constant, use a default-on diagnostic.
4802 // TODO: this should happen for bitfield stores, too.
4803 llvm::APSInt Value(32);
4804 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004805 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004806 return;
4807
John McCall091f23f2010-11-09 22:22:12 +00004808 std::string PrettySourceValue = Value.toString(10);
4809 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4810
Ted Kremenek5e745da2011-10-22 02:37:33 +00004811 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4812 S.PDiag(diag::warn_impcast_integer_precision_constant)
4813 << PrettySourceValue << PrettyTargetValue
4814 << E->getType() << T << E->getSourceRange()
4815 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004816 return;
4817 }
4818
Chris Lattnerb792b302011-06-14 04:51:15 +00004819 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004820 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004821 return;
4822
David Blaikie37050842012-04-12 22:40:54 +00004823 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004824 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4825 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004826 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004827 }
4828
4829 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4830 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4831 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004832
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004833 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004834 return;
4835
John McCall323ed742010-05-06 08:58:33 +00004836 unsigned DiagID = diag::warn_impcast_integer_sign;
4837
4838 // Traditionally, gcc has warned about this under -Wsign-compare.
4839 // We also want to warn about it in -Wconversion.
4840 // So if -Wconversion is off, use a completely identical diagnostic
4841 // in the sign-compare group.
4842 // The conditional-checking code will
4843 if (ICContext) {
4844 DiagID = diag::warn_impcast_integer_sign_conditional;
4845 *ICContext = true;
4846 }
4847
John McCallb4eb64d2010-10-08 02:01:28 +00004848 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004849 }
4850
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004851 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004852 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4853 // type, to give us better diagnostics.
4854 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004855 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4857 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4858 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4859 SourceType = S.Context.getTypeDeclType(Enum);
4860 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4861 }
4862 }
4863
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004864 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4865 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4866 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004867 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004868 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004869 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004870 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004871 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004872 return;
4873
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004874 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004875 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004876 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004877
John McCall51313c32010-01-04 23:31:57 +00004878 return;
4879}
4880
David Blaikie9fb1ac52012-05-15 21:57:38 +00004881void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4882 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004883
4884void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004885 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004886 E = E->IgnoreParenImpCasts();
4887
4888 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004889 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004890
John McCallb4eb64d2010-10-08 02:01:28 +00004891 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004892 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004893 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004894 return;
4895}
4896
David Blaikie9fb1ac52012-05-15 21:57:38 +00004897void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4898 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004899 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004900
4901 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004902 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4903 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004904
4905 // If -Wconversion would have warned about either of the candidates
4906 // for a signedness conversion to the context type...
4907 if (!Suspicious) return;
4908
4909 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004910 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4911 CC))
John McCall323ed742010-05-06 08:58:33 +00004912 return;
4913
John McCall323ed742010-05-06 08:58:33 +00004914 // ...then check whether it would have warned about either of the
4915 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004916 if (E->getType() == T) return;
4917
4918 Suspicious = false;
4919 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4920 E->getType(), CC, &Suspicious);
4921 if (!Suspicious)
4922 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004923 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004924}
4925
4926/// AnalyzeImplicitConversions - Find and report any interesting
4927/// implicit conversions in the given expression. There are a couple
4928/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004929void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004930 QualType T = OrigE->getType();
4931 Expr *E = OrigE->IgnoreParenImpCasts();
4932
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004933 if (E->isTypeDependent() || E->isValueDependent())
4934 return;
4935
John McCall323ed742010-05-06 08:58:33 +00004936 // For conditional operators, we analyze the arguments as if they
4937 // were being fed directly into the output.
4938 if (isa<ConditionalOperator>(E)) {
4939 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004940 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004941 return;
4942 }
4943
Hans Wennborg88617a22012-08-28 15:44:30 +00004944 // Check implicit argument conversions for function calls.
4945 if (CallExpr *Call = dyn_cast<CallExpr>(E))
4946 CheckImplicitArgumentConversions(S, Call, CC);
4947
John McCall323ed742010-05-06 08:58:33 +00004948 // Go ahead and check any implicit conversions we might have skipped.
4949 // The non-canonical typecheck is just an optimization;
4950 // CheckImplicitConversion will filter out dead implicit conversions.
4951 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004952 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004953
4954 // Now continue drilling into this expression.
4955
4956 // Skip past explicit casts.
4957 if (isa<ExplicitCastExpr>(E)) {
4958 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004959 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004960 }
4961
John McCallbeb22aa2010-11-09 23:24:47 +00004962 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4963 // Do a somewhat different check with comparison operators.
4964 if (BO->isComparisonOp())
4965 return AnalyzeComparison(S, BO);
4966
Eli Friedman0fa06382012-01-26 23:34:06 +00004967 // And with simple assignments.
4968 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004969 return AnalyzeAssignment(S, BO);
4970 }
John McCall323ed742010-05-06 08:58:33 +00004971
4972 // These break the otherwise-useful invariant below. Fortunately,
4973 // we don't really need to recurse into them, because any internal
4974 // expressions should have been analyzed already when they were
4975 // built into statements.
4976 if (isa<StmtExpr>(E)) return;
4977
4978 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004979 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004980
4981 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004982 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004983 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4984 bool IsLogicalOperator = BO && BO->isLogicalOp();
4985 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004986 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004987 if (!ChildExpr)
4988 continue;
4989
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004990 if (IsLogicalOperator &&
4991 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4992 // Ignore checking string literals that are in logical operators.
4993 continue;
4994 AnalyzeImplicitConversions(S, ChildExpr, CC);
4995 }
John McCall323ed742010-05-06 08:58:33 +00004996}
4997
4998} // end anonymous namespace
4999
5000/// Diagnoses "dangerous" implicit conversions within the given
5001/// expression (which is a full expression). Implements -Wconversion
5002/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005003///
5004/// \param CC the "context" location of the implicit conversion, i.e.
5005/// the most location of the syntactic entity requiring the implicit
5006/// conversion
5007void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005008 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005009 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005010 return;
5011
5012 // Don't diagnose for value- or type-dependent expressions.
5013 if (E->isTypeDependent() || E->isValueDependent())
5014 return;
5015
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005016 // Check for array bounds violations in cases where the check isn't triggered
5017 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5018 // ArraySubscriptExpr is on the RHS of a variable initialization.
5019 CheckArrayAccess(E);
5020
John McCallb4eb64d2010-10-08 02:01:28 +00005021 // This is not the right CC for (e.g.) a variable initialization.
5022 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005023}
5024
John McCall15d7d122010-11-11 03:21:53 +00005025void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5026 FieldDecl *BitField,
5027 Expr *Init) {
5028 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5029}
5030
Mike Stumpf8c49212010-01-21 03:59:47 +00005031/// CheckParmsForFunctionDef - Check that the parameters of the given
5032/// function are appropriate for the definition of a function. This
5033/// takes care of any checks that cannot be performed on the
5034/// declaration itself, e.g., that the types of each of the function
5035/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005036bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5037 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005038 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005039 for (; P != PEnd; ++P) {
5040 ParmVarDecl *Param = *P;
5041
Mike Stumpf8c49212010-01-21 03:59:47 +00005042 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5043 // function declarator that is part of a function definition of
5044 // that function shall not have incomplete type.
5045 //
5046 // This is also C++ [dcl.fct]p6.
5047 if (!Param->isInvalidDecl() &&
5048 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005049 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005050 Param->setInvalidDecl();
5051 HasInvalidParm = true;
5052 }
5053
5054 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5055 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005056 if (CheckParameterNames &&
5057 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005058 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005059 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005060 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005061
5062 // C99 6.7.5.3p12:
5063 // If the function declarator is not part of a definition of that
5064 // function, parameters may have incomplete type and may use the [*]
5065 // notation in their sequences of declarator specifiers to specify
5066 // variable length array types.
5067 QualType PType = Param->getOriginalType();
5068 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5069 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00005070 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005071 // information is added for it.
5072 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5073 }
5074 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005075 }
5076
5077 return HasInvalidParm;
5078}
John McCallb7f4ffe2010-08-12 21:44:57 +00005079
5080/// CheckCastAlign - Implements -Wcast-align, which warns when a
5081/// pointer cast increases the alignment requirements.
5082void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5083 // This is actually a lot of work to potentially be doing on every
5084 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005085 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5086 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005087 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005088 return;
5089
5090 // Ignore dependent types.
5091 if (T->isDependentType() || Op->getType()->isDependentType())
5092 return;
5093
5094 // Require that the destination be a pointer type.
5095 const PointerType *DestPtr = T->getAs<PointerType>();
5096 if (!DestPtr) return;
5097
5098 // If the destination has alignment 1, we're done.
5099 QualType DestPointee = DestPtr->getPointeeType();
5100 if (DestPointee->isIncompleteType()) return;
5101 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5102 if (DestAlign.isOne()) return;
5103
5104 // Require that the source be a pointer type.
5105 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5106 if (!SrcPtr) return;
5107 QualType SrcPointee = SrcPtr->getPointeeType();
5108
5109 // Whitelist casts from cv void*. We already implicitly
5110 // whitelisted casts to cv void*, since they have alignment 1.
5111 // Also whitelist casts involving incomplete types, which implicitly
5112 // includes 'void'.
5113 if (SrcPointee->isIncompleteType()) return;
5114
5115 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5116 if (SrcAlign >= DestAlign) return;
5117
5118 Diag(TRange.getBegin(), diag::warn_cast_align)
5119 << Op->getType() << T
5120 << static_cast<unsigned>(SrcAlign.getQuantity())
5121 << static_cast<unsigned>(DestAlign.getQuantity())
5122 << TRange << Op->getSourceRange();
5123}
5124
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005125static const Type* getElementType(const Expr *BaseExpr) {
5126 const Type* EltType = BaseExpr->getType().getTypePtr();
5127 if (EltType->isAnyPointerType())
5128 return EltType->getPointeeType().getTypePtr();
5129 else if (EltType->isArrayType())
5130 return EltType->getBaseElementTypeUnsafe();
5131 return EltType;
5132}
5133
Chandler Carruthc2684342011-08-05 09:10:50 +00005134/// \brief Check whether this array fits the idiom of a size-one tail padded
5135/// array member of a struct.
5136///
5137/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5138/// commonly used to emulate flexible arrays in C89 code.
5139static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5140 const NamedDecl *ND) {
5141 if (Size != 1 || !ND) return false;
5142
5143 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5144 if (!FD) return false;
5145
5146 // Don't consider sizes resulting from macro expansions or template argument
5147 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005148
5149 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005150 while (TInfo) {
5151 TypeLoc TL = TInfo->getTypeLoc();
5152 // Look through typedefs.
5153 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5154 if (TTL) {
5155 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5156 TInfo = TDL->getTypeSourceInfo();
5157 continue;
5158 }
5159 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5160 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005161 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5162 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005163 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005164 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005165
5166 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005167 if (!RD) return false;
5168 if (RD->isUnion()) return false;
5169 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5170 if (!CRD->isStandardLayout()) return false;
5171 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005172
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005173 // See if this is the last field decl in the record.
5174 const Decl *D = FD;
5175 while ((D = D->getNextDeclInContext()))
5176 if (isa<FieldDecl>(D))
5177 return false;
5178 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005179}
5180
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005181void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005182 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005183 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005184 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005185 if (IndexExpr->isValueDependent())
5186 return;
5187
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005188 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005189 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005190 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005191 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005192 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005193 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005194
Chandler Carruth34064582011-02-17 20:55:08 +00005195 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005196 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005197 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005198 if (IndexNegated)
5199 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005200
Chandler Carruthba447122011-08-05 08:07:29 +00005201 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005202 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5203 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005204 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005205 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005206
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005207 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005208 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005209 if (!size.isStrictlyPositive())
5210 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005211
5212 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005213 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005214 // Make sure we're comparing apples to apples when comparing index to size
5215 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5216 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005217 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005218 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005219 if (ptrarith_typesize != array_typesize) {
5220 // There's a cast to a different size type involved
5221 uint64_t ratio = array_typesize / ptrarith_typesize;
5222 // TODO: Be smarter about handling cases where array_typesize is not a
5223 // multiple of ptrarith_typesize
5224 if (ptrarith_typesize * ratio == array_typesize)
5225 size *= llvm::APInt(size.getBitWidth(), ratio);
5226 }
5227 }
5228
Chandler Carruth34064582011-02-17 20:55:08 +00005229 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005230 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005231 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005232 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005233
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005234 // For array subscripting the index must be less than size, but for pointer
5235 // arithmetic also allow the index (offset) to be equal to size since
5236 // computing the next address after the end of the array is legal and
5237 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005238 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005239 return;
5240
5241 // Also don't warn for arrays of size 1 which are members of some
5242 // structure. These are often used to approximate flexible arrays in C89
5243 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005244 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005245 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005246
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005247 // Suppress the warning if the subscript expression (as identified by the
5248 // ']' location) and the index expression are both from macro expansions
5249 // within a system header.
5250 if (ASE) {
5251 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5252 ASE->getRBracketLoc());
5253 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5254 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5255 IndexExpr->getLocStart());
5256 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5257 return;
5258 }
5259 }
5260
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005261 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005262 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005263 DiagID = diag::warn_array_index_exceeds_bounds;
5264
5265 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5266 PDiag(DiagID) << index.toString(10, true)
5267 << size.toString(10, true)
5268 << (unsigned)size.getLimitedValue(~0U)
5269 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005270 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005271 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005272 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005273 DiagID = diag::warn_ptr_arith_precedes_bounds;
5274 if (index.isNegative()) index = -index;
5275 }
5276
5277 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5278 PDiag(DiagID) << index.toString(10, true)
5279 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005280 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005281
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005282 if (!ND) {
5283 // Try harder to find a NamedDecl to point at in the note.
5284 while (const ArraySubscriptExpr *ASE =
5285 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5286 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5287 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5288 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5289 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5290 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5291 }
5292
Chandler Carruth35001ca2011-02-17 21:10:52 +00005293 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005294 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5295 PDiag(diag::note_array_index_out_of_bounds)
5296 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005297}
5298
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005299void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005300 int AllowOnePastEnd = 0;
5301 while (expr) {
5302 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005303 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005304 case Stmt::ArraySubscriptExprClass: {
5305 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005306 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005307 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005308 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005309 }
5310 case Stmt::UnaryOperatorClass: {
5311 // Only unwrap the * and & unary operators
5312 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5313 expr = UO->getSubExpr();
5314 switch (UO->getOpcode()) {
5315 case UO_AddrOf:
5316 AllowOnePastEnd++;
5317 break;
5318 case UO_Deref:
5319 AllowOnePastEnd--;
5320 break;
5321 default:
5322 return;
5323 }
5324 break;
5325 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005326 case Stmt::ConditionalOperatorClass: {
5327 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5328 if (const Expr *lhs = cond->getLHS())
5329 CheckArrayAccess(lhs);
5330 if (const Expr *rhs = cond->getRHS())
5331 CheckArrayAccess(rhs);
5332 return;
5333 }
5334 default:
5335 return;
5336 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005337 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005338}
John McCallf85e1932011-06-15 23:02:42 +00005339
5340//===--- CHECK: Objective-C retain cycles ----------------------------------//
5341
5342namespace {
5343 struct RetainCycleOwner {
5344 RetainCycleOwner() : Variable(0), Indirect(false) {}
5345 VarDecl *Variable;
5346 SourceRange Range;
5347 SourceLocation Loc;
5348 bool Indirect;
5349
5350 void setLocsFrom(Expr *e) {
5351 Loc = e->getExprLoc();
5352 Range = e->getSourceRange();
5353 }
5354 };
5355}
5356
5357/// Consider whether capturing the given variable can possibly lead to
5358/// a retain cycle.
5359static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5360 // In ARC, it's captured strongly iff the variable has __strong
5361 // lifetime. In MRR, it's captured strongly if the variable is
5362 // __block and has an appropriate type.
5363 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5364 return false;
5365
5366 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00005367 if (ref)
5368 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00005369 return true;
5370}
5371
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005372static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005373 while (true) {
5374 e = e->IgnoreParens();
5375 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5376 switch (cast->getCastKind()) {
5377 case CK_BitCast:
5378 case CK_LValueBitCast:
5379 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005380 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005381 e = cast->getSubExpr();
5382 continue;
5383
John McCallf85e1932011-06-15 23:02:42 +00005384 default:
5385 return false;
5386 }
5387 }
5388
5389 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5390 ObjCIvarDecl *ivar = ref->getDecl();
5391 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5392 return false;
5393
5394 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005395 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005396 return false;
5397
5398 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5399 owner.Indirect = true;
5400 return true;
5401 }
5402
5403 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5404 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5405 if (!var) return false;
5406 return considerVariable(var, ref, owner);
5407 }
5408
John McCallf85e1932011-06-15 23:02:42 +00005409 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5410 if (member->isArrow()) return false;
5411
5412 // Don't count this as an indirect ownership.
5413 e = member->getBase();
5414 continue;
5415 }
5416
John McCall4b9c2d22011-11-06 09:01:30 +00005417 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5418 // Only pay attention to pseudo-objects on property references.
5419 ObjCPropertyRefExpr *pre
5420 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5421 ->IgnoreParens());
5422 if (!pre) return false;
5423 if (pre->isImplicitProperty()) return false;
5424 ObjCPropertyDecl *property = pre->getExplicitProperty();
5425 if (!property->isRetaining() &&
5426 !(property->getPropertyIvarDecl() &&
5427 property->getPropertyIvarDecl()->getType()
5428 .getObjCLifetime() == Qualifiers::OCL_Strong))
5429 return false;
5430
5431 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005432 if (pre->isSuperReceiver()) {
5433 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5434 if (!owner.Variable)
5435 return false;
5436 owner.Loc = pre->getLocation();
5437 owner.Range = pre->getSourceRange();
5438 return true;
5439 }
John McCall4b9c2d22011-11-06 09:01:30 +00005440 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5441 ->getSourceExpr());
5442 continue;
5443 }
5444
John McCallf85e1932011-06-15 23:02:42 +00005445 // Array ivars?
5446
5447 return false;
5448 }
5449}
5450
5451namespace {
5452 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5453 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5454 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5455 Variable(variable), Capturer(0) {}
5456
5457 VarDecl *Variable;
5458 Expr *Capturer;
5459
5460 void VisitDeclRefExpr(DeclRefExpr *ref) {
5461 if (ref->getDecl() == Variable && !Capturer)
5462 Capturer = ref;
5463 }
5464
John McCallf85e1932011-06-15 23:02:42 +00005465 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5466 if (Capturer) return;
5467 Visit(ref->getBase());
5468 if (Capturer && ref->isFreeIvar())
5469 Capturer = ref;
5470 }
5471
5472 void VisitBlockExpr(BlockExpr *block) {
5473 // Look inside nested blocks
5474 if (block->getBlockDecl()->capturesVariable(Variable))
5475 Visit(block->getBlockDecl()->getBody());
5476 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005477
5478 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5479 if (Capturer) return;
5480 if (OVE->getSourceExpr())
5481 Visit(OVE->getSourceExpr());
5482 }
John McCallf85e1932011-06-15 23:02:42 +00005483 };
5484}
5485
5486/// Check whether the given argument is a block which captures a
5487/// variable.
5488static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5489 assert(owner.Variable && owner.Loc.isValid());
5490
5491 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00005492
5493 // Look through [^{...} copy] and Block_copy(^{...}).
5494 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5495 Selector Cmd = ME->getSelector();
5496 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5497 e = ME->getInstanceReceiver();
5498 if (!e)
5499 return 0;
5500 e = e->IgnoreParenCasts();
5501 }
5502 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5503 if (CE->getNumArgs() == 1) {
5504 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
5505 if (Fn && Fn->getIdentifier()->isStr("_Block_copy"))
5506 e = CE->getArg(0)->IgnoreParenCasts();
5507 }
5508 }
5509
John McCallf85e1932011-06-15 23:02:42 +00005510 BlockExpr *block = dyn_cast<BlockExpr>(e);
5511 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5512 return 0;
5513
5514 FindCaptureVisitor visitor(S.Context, owner.Variable);
5515 visitor.Visit(block->getBlockDecl()->getBody());
5516 return visitor.Capturer;
5517}
5518
5519static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5520 RetainCycleOwner &owner) {
5521 assert(capturer);
5522 assert(owner.Variable && owner.Loc.isValid());
5523
5524 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5525 << owner.Variable << capturer->getSourceRange();
5526 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5527 << owner.Indirect << owner.Range;
5528}
5529
5530/// Check for a keyword selector that starts with the word 'add' or
5531/// 'set'.
5532static bool isSetterLikeSelector(Selector sel) {
5533 if (sel.isUnarySelector()) return false;
5534
Chris Lattner5f9e2722011-07-23 10:55:15 +00005535 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005536 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005537 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005538 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005539 else if (str.startswith("add")) {
5540 // Specially whitelist 'addOperationWithBlock:'.
5541 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5542 return false;
5543 str = str.substr(3);
5544 }
John McCallf85e1932011-06-15 23:02:42 +00005545 else
5546 return false;
5547
5548 if (str.empty()) return true;
5549 return !islower(str.front());
5550}
5551
5552/// Check a message send to see if it's likely to cause a retain cycle.
5553void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5554 // Only check instance methods whose selector looks like a setter.
5555 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5556 return;
5557
5558 // Try to find a variable that the receiver is strongly owned by.
5559 RetainCycleOwner owner;
5560 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005561 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005562 return;
5563 } else {
5564 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5565 owner.Variable = getCurMethodDecl()->getSelfDecl();
5566 owner.Loc = msg->getSuperLoc();
5567 owner.Range = msg->getSuperLoc();
5568 }
5569
5570 // Check whether the receiver is captured by any of the arguments.
5571 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5572 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5573 return diagnoseRetainCycle(*this, capturer, owner);
5574}
5575
5576/// Check a property assign to see if it's likely to cause a retain cycle.
5577void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5578 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005579 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005580 return;
5581
5582 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5583 diagnoseRetainCycle(*this, capturer, owner);
5584}
5585
Jordan Rosee10f4d32012-09-15 02:48:31 +00005586void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5587 RetainCycleOwner Owner;
5588 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5589 return;
5590
5591 // Because we don't have an expression for the variable, we have to set the
5592 // location explicitly here.
5593 Owner.Loc = Var->getLocation();
5594 Owner.Range = Var->getSourceRange();
5595
5596 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5597 diagnoseRetainCycle(*this, Capturer, Owner);
5598}
5599
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005600bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005601 QualType LHS, Expr *RHS) {
5602 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5603 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005604 return false;
5605 // strip off any implicit cast added to get to the one arc-specific
5606 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005607 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005608 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005609 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005610 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005611 return true;
5612 }
5613 RHS = cast->getSubExpr();
5614 }
5615 return false;
John McCallf85e1932011-06-15 23:02:42 +00005616}
5617
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005618void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5619 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005620 QualType LHSType;
5621 // PropertyRef on LHS type need be directly obtained from
5622 // its declaration as it has a PsuedoType.
5623 ObjCPropertyRefExpr *PRE
5624 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5625 if (PRE && !PRE->isImplicitProperty()) {
5626 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5627 if (PD)
5628 LHSType = PD->getType();
5629 }
5630
5631 if (LHSType.isNull())
5632 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005633 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5634 return;
5635 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5636 // FIXME. Check for other life times.
5637 if (LT != Qualifiers::OCL_None)
5638 return;
5639
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005640 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005641 if (PRE->isImplicitProperty())
5642 return;
5643 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5644 if (!PD)
5645 return;
5646
5647 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005648 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5649 // when 'assign' attribute was not explicitly specified
5650 // by user, ignore it and rely on property type itself
5651 // for lifetime info.
5652 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5653 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5654 LHSType->isObjCRetainableType())
5655 return;
5656
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005657 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005658 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005659 Diag(Loc, diag::warn_arc_retained_property_assign)
5660 << RHS->getSourceRange();
5661 return;
5662 }
5663 RHS = cast->getSubExpr();
5664 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005665 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005666 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5667 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5668 if (cast->getCastKind() == CK_ARCConsumeObject) {
5669 Diag(Loc, diag::warn_arc_retained_assign)
5670 << 0 << 0<< RHS->getSourceRange();
5671 return;
5672 }
5673 RHS = cast->getSubExpr();
5674 }
5675 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005676 }
5677}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005678
5679//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5680
5681namespace {
5682bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5683 SourceLocation StmtLoc,
5684 const NullStmt *Body) {
5685 // Do not warn if the body is a macro that expands to nothing, e.g:
5686 //
5687 // #define CALL(x)
5688 // if (condition)
5689 // CALL(0);
5690 //
5691 if (Body->hasLeadingEmptyMacro())
5692 return false;
5693
5694 // Get line numbers of statement and body.
5695 bool StmtLineInvalid;
5696 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5697 &StmtLineInvalid);
5698 if (StmtLineInvalid)
5699 return false;
5700
5701 bool BodyLineInvalid;
5702 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5703 &BodyLineInvalid);
5704 if (BodyLineInvalid)
5705 return false;
5706
5707 // Warn if null statement and body are on the same line.
5708 if (StmtLine != BodyLine)
5709 return false;
5710
5711 return true;
5712}
5713} // Unnamed namespace
5714
5715void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5716 const Stmt *Body,
5717 unsigned DiagID) {
5718 // Since this is a syntactic check, don't emit diagnostic for template
5719 // instantiations, this just adds noise.
5720 if (CurrentInstantiationScope)
5721 return;
5722
5723 // The body should be a null statement.
5724 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5725 if (!NBody)
5726 return;
5727
5728 // Do the usual checks.
5729 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5730 return;
5731
5732 Diag(NBody->getSemiLoc(), DiagID);
5733 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5734}
5735
5736void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5737 const Stmt *PossibleBody) {
5738 assert(!CurrentInstantiationScope); // Ensured by caller
5739
5740 SourceLocation StmtLoc;
5741 const Stmt *Body;
5742 unsigned DiagID;
5743 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5744 StmtLoc = FS->getRParenLoc();
5745 Body = FS->getBody();
5746 DiagID = diag::warn_empty_for_body;
5747 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5748 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5749 Body = WS->getBody();
5750 DiagID = diag::warn_empty_while_body;
5751 } else
5752 return; // Neither `for' nor `while'.
5753
5754 // The body should be a null statement.
5755 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5756 if (!NBody)
5757 return;
5758
5759 // Skip expensive checks if diagnostic is disabled.
5760 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5761 DiagnosticsEngine::Ignored)
5762 return;
5763
5764 // Do the usual checks.
5765 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5766 return;
5767
5768 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5769 // noise level low, emit diagnostics only if for/while is followed by a
5770 // CompoundStmt, e.g.:
5771 // for (int i = 0; i < n; i++);
5772 // {
5773 // a(i);
5774 // }
5775 // or if for/while is followed by a statement with more indentation
5776 // than for/while itself:
5777 // for (int i = 0; i < n; i++);
5778 // a(i);
5779 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5780 if (!ProbableTypo) {
5781 bool BodyColInvalid;
5782 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5783 PossibleBody->getLocStart(),
5784 &BodyColInvalid);
5785 if (BodyColInvalid)
5786 return;
5787
5788 bool StmtColInvalid;
5789 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5790 S->getLocStart(),
5791 &StmtColInvalid);
5792 if (StmtColInvalid)
5793 return;
5794
5795 if (BodyCol > StmtCol)
5796 ProbableTypo = true;
5797 }
5798
5799 if (ProbableTypo) {
5800 Diag(NBody->getSemiLoc(), DiagID);
5801 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5802 }
5803}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00005804
5805//===--- Layout compatibility ----------------------------------------------//
5806
5807namespace {
5808
5809bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5810
5811/// \brief Check if two enumeration types are layout-compatible.
5812bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5813 // C++11 [dcl.enum] p8:
5814 // Two enumeration types are layout-compatible if they have the same
5815 // underlying type.
5816 return ED1->isComplete() && ED2->isComplete() &&
5817 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5818}
5819
5820/// \brief Check if two fields are layout-compatible.
5821bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5822 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5823 return false;
5824
5825 if (Field1->isBitField() != Field2->isBitField())
5826 return false;
5827
5828 if (Field1->isBitField()) {
5829 // Make sure that the bit-fields are the same length.
5830 unsigned Bits1 = Field1->getBitWidthValue(C);
5831 unsigned Bits2 = Field2->getBitWidthValue(C);
5832
5833 if (Bits1 != Bits2)
5834 return false;
5835 }
5836
5837 return true;
5838}
5839
5840/// \brief Check if two standard-layout structs are layout-compatible.
5841/// (C++11 [class.mem] p17)
5842bool isLayoutCompatibleStruct(ASTContext &C,
5843 RecordDecl *RD1,
5844 RecordDecl *RD2) {
5845 // If both records are C++ classes, check that base classes match.
5846 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5847 // If one of records is a CXXRecordDecl we are in C++ mode,
5848 // thus the other one is a CXXRecordDecl, too.
5849 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5850 // Check number of base classes.
5851 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5852 return false;
5853
5854 // Check the base classes.
5855 for (CXXRecordDecl::base_class_const_iterator
5856 Base1 = D1CXX->bases_begin(),
5857 BaseEnd1 = D1CXX->bases_end(),
5858 Base2 = D2CXX->bases_begin();
5859 Base1 != BaseEnd1;
5860 ++Base1, ++Base2) {
5861 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5862 return false;
5863 }
5864 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5865 // If only RD2 is a C++ class, it should have zero base classes.
5866 if (D2CXX->getNumBases() > 0)
5867 return false;
5868 }
5869
5870 // Check the fields.
5871 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5872 Field2End = RD2->field_end(),
5873 Field1 = RD1->field_begin(),
5874 Field1End = RD1->field_end();
5875 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5876 if (!isLayoutCompatible(C, *Field1, *Field2))
5877 return false;
5878 }
5879 if (Field1 != Field1End || Field2 != Field2End)
5880 return false;
5881
5882 return true;
5883}
5884
5885/// \brief Check if two standard-layout unions are layout-compatible.
5886/// (C++11 [class.mem] p18)
5887bool isLayoutCompatibleUnion(ASTContext &C,
5888 RecordDecl *RD1,
5889 RecordDecl *RD2) {
5890 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5891 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5892 Field2End = RD2->field_end();
5893 Field2 != Field2End; ++Field2) {
5894 UnmatchedFields.insert(*Field2);
5895 }
5896
5897 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5898 Field1End = RD1->field_end();
5899 Field1 != Field1End; ++Field1) {
5900 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5901 I = UnmatchedFields.begin(),
5902 E = UnmatchedFields.end();
5903
5904 for ( ; I != E; ++I) {
5905 if (isLayoutCompatible(C, *Field1, *I)) {
5906 bool Result = UnmatchedFields.erase(*I);
5907 (void) Result;
5908 assert(Result);
5909 break;
5910 }
5911 }
5912 if (I == E)
5913 return false;
5914 }
5915
5916 return UnmatchedFields.empty();
5917}
5918
5919bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5920 if (RD1->isUnion() != RD2->isUnion())
5921 return false;
5922
5923 if (RD1->isUnion())
5924 return isLayoutCompatibleUnion(C, RD1, RD2);
5925 else
5926 return isLayoutCompatibleStruct(C, RD1, RD2);
5927}
5928
5929/// \brief Check if two types are layout-compatible in C++11 sense.
5930bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
5931 if (T1.isNull() || T2.isNull())
5932 return false;
5933
5934 // C++11 [basic.types] p11:
5935 // If two types T1 and T2 are the same type, then T1 and T2 are
5936 // layout-compatible types.
5937 if (C.hasSameType(T1, T2))
5938 return true;
5939
5940 T1 = T1.getCanonicalType().getUnqualifiedType();
5941 T2 = T2.getCanonicalType().getUnqualifiedType();
5942
5943 const Type::TypeClass TC1 = T1->getTypeClass();
5944 const Type::TypeClass TC2 = T2->getTypeClass();
5945
5946 if (TC1 != TC2)
5947 return false;
5948
5949 if (TC1 == Type::Enum) {
5950 return isLayoutCompatible(C,
5951 cast<EnumType>(T1)->getDecl(),
5952 cast<EnumType>(T2)->getDecl());
5953 } else if (TC1 == Type::Record) {
5954 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
5955 return false;
5956
5957 return isLayoutCompatible(C,
5958 cast<RecordType>(T1)->getDecl(),
5959 cast<RecordType>(T2)->getDecl());
5960 }
5961
5962 return false;
5963}
5964}
5965
5966//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
5967
5968namespace {
5969/// \brief Given a type tag expression find the type tag itself.
5970///
5971/// \param TypeExpr Type tag expression, as it appears in user's code.
5972///
5973/// \param VD Declaration of an identifier that appears in a type tag.
5974///
5975/// \param MagicValue Type tag magic value.
5976bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
5977 const ValueDecl **VD, uint64_t *MagicValue) {
5978 while(true) {
5979 if (!TypeExpr)
5980 return false;
5981
5982 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
5983
5984 switch (TypeExpr->getStmtClass()) {
5985 case Stmt::UnaryOperatorClass: {
5986 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
5987 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
5988 TypeExpr = UO->getSubExpr();
5989 continue;
5990 }
5991 return false;
5992 }
5993
5994 case Stmt::DeclRefExprClass: {
5995 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
5996 *VD = DRE->getDecl();
5997 return true;
5998 }
5999
6000 case Stmt::IntegerLiteralClass: {
6001 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6002 llvm::APInt MagicValueAPInt = IL->getValue();
6003 if (MagicValueAPInt.getActiveBits() <= 64) {
6004 *MagicValue = MagicValueAPInt.getZExtValue();
6005 return true;
6006 } else
6007 return false;
6008 }
6009
6010 case Stmt::BinaryConditionalOperatorClass:
6011 case Stmt::ConditionalOperatorClass: {
6012 const AbstractConditionalOperator *ACO =
6013 cast<AbstractConditionalOperator>(TypeExpr);
6014 bool Result;
6015 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6016 if (Result)
6017 TypeExpr = ACO->getTrueExpr();
6018 else
6019 TypeExpr = ACO->getFalseExpr();
6020 continue;
6021 }
6022 return false;
6023 }
6024
6025 case Stmt::BinaryOperatorClass: {
6026 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6027 if (BO->getOpcode() == BO_Comma) {
6028 TypeExpr = BO->getRHS();
6029 continue;
6030 }
6031 return false;
6032 }
6033
6034 default:
6035 return false;
6036 }
6037 }
6038}
6039
6040/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6041///
6042/// \param TypeExpr Expression that specifies a type tag.
6043///
6044/// \param MagicValues Registered magic values.
6045///
6046/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6047/// kind.
6048///
6049/// \param TypeInfo Information about the corresponding C type.
6050///
6051/// \returns true if the corresponding C type was found.
6052bool GetMatchingCType(
6053 const IdentifierInfo *ArgumentKind,
6054 const Expr *TypeExpr, const ASTContext &Ctx,
6055 const llvm::DenseMap<Sema::TypeTagMagicValue,
6056 Sema::TypeTagData> *MagicValues,
6057 bool &FoundWrongKind,
6058 Sema::TypeTagData &TypeInfo) {
6059 FoundWrongKind = false;
6060
6061 // Variable declaration that has type_tag_for_datatype attribute.
6062 const ValueDecl *VD = NULL;
6063
6064 uint64_t MagicValue;
6065
6066 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6067 return false;
6068
6069 if (VD) {
6070 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6071 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6072 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6073 I != E; ++I) {
6074 if (I->getArgumentKind() != ArgumentKind) {
6075 FoundWrongKind = true;
6076 return false;
6077 }
6078 TypeInfo.Type = I->getMatchingCType();
6079 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6080 TypeInfo.MustBeNull = I->getMustBeNull();
6081 return true;
6082 }
6083 return false;
6084 }
6085
6086 if (!MagicValues)
6087 return false;
6088
6089 llvm::DenseMap<Sema::TypeTagMagicValue,
6090 Sema::TypeTagData>::const_iterator I =
6091 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6092 if (I == MagicValues->end())
6093 return false;
6094
6095 TypeInfo = I->second;
6096 return true;
6097}
6098} // unnamed namespace
6099
6100void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6101 uint64_t MagicValue, QualType Type,
6102 bool LayoutCompatible,
6103 bool MustBeNull) {
6104 if (!TypeTagForDatatypeMagicValues)
6105 TypeTagForDatatypeMagicValues.reset(
6106 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6107
6108 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6109 (*TypeTagForDatatypeMagicValues)[Magic] =
6110 TypeTagData(Type, LayoutCompatible, MustBeNull);
6111}
6112
6113namespace {
6114bool IsSameCharType(QualType T1, QualType T2) {
6115 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6116 if (!BT1)
6117 return false;
6118
6119 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6120 if (!BT2)
6121 return false;
6122
6123 BuiltinType::Kind T1Kind = BT1->getKind();
6124 BuiltinType::Kind T2Kind = BT2->getKind();
6125
6126 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6127 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6128 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6129 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6130}
6131} // unnamed namespace
6132
6133void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6134 const Expr * const *ExprArgs) {
6135 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6136 bool IsPointerAttr = Attr->getIsPointer();
6137
6138 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6139 bool FoundWrongKind;
6140 TypeTagData TypeInfo;
6141 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6142 TypeTagForDatatypeMagicValues.get(),
6143 FoundWrongKind, TypeInfo)) {
6144 if (FoundWrongKind)
6145 Diag(TypeTagExpr->getExprLoc(),
6146 diag::warn_type_tag_for_datatype_wrong_kind)
6147 << TypeTagExpr->getSourceRange();
6148 return;
6149 }
6150
6151 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6152 if (IsPointerAttr) {
6153 // Skip implicit cast of pointer to `void *' (as a function argument).
6154 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6155 if (ICE->getType()->isVoidPointerType())
6156 ArgumentExpr = ICE->getSubExpr();
6157 }
6158 QualType ArgumentType = ArgumentExpr->getType();
6159
6160 // Passing a `void*' pointer shouldn't trigger a warning.
6161 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6162 return;
6163
6164 if (TypeInfo.MustBeNull) {
6165 // Type tag with matching void type requires a null pointer.
6166 if (!ArgumentExpr->isNullPointerConstant(Context,
6167 Expr::NPC_ValueDependentIsNotNull)) {
6168 Diag(ArgumentExpr->getExprLoc(),
6169 diag::warn_type_safety_null_pointer_required)
6170 << ArgumentKind->getName()
6171 << ArgumentExpr->getSourceRange()
6172 << TypeTagExpr->getSourceRange();
6173 }
6174 return;
6175 }
6176
6177 QualType RequiredType = TypeInfo.Type;
6178 if (IsPointerAttr)
6179 RequiredType = Context.getPointerType(RequiredType);
6180
6181 bool mismatch = false;
6182 if (!TypeInfo.LayoutCompatible) {
6183 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6184
6185 // C++11 [basic.fundamental] p1:
6186 // Plain char, signed char, and unsigned char are three distinct types.
6187 //
6188 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6189 // char' depending on the current char signedness mode.
6190 if (mismatch)
6191 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6192 RequiredType->getPointeeType())) ||
6193 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6194 mismatch = false;
6195 } else
6196 if (IsPointerAttr)
6197 mismatch = !isLayoutCompatible(Context,
6198 ArgumentType->getPointeeType(),
6199 RequiredType->getPointeeType());
6200 else
6201 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6202
6203 if (mismatch)
6204 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6205 << ArgumentType << ArgumentKind->getName()
6206 << TypeInfo.LayoutCompatible << RequiredType
6207 << ArgumentExpr->getSourceRange()
6208 << TypeTagExpr->getSourceRange();
6209}