blob: f5296ce70fbb472b123015173dd81df4bc99a7a9 [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 McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
John McCall60d7b3a2010-08-24 06:29:42 +000098ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000099Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000100 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000101
Chris Lattner946928f2010-10-01 23:23:24 +0000102 // Find out if any arguments are required to be integer constant expressions.
103 unsigned ICEArguments = 0;
104 ASTContext::GetBuiltinTypeError Error;
105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106 if (Error != ASTContext::GE_None)
107 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
108
109 // If any arguments are required to be ICE's, check and diagnose.
110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111 // Skip arguments not required to be ICE's.
112 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114 llvm::APSInt Result;
115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116 return true;
117 ICEArguments &= ~(1 << ArgNo);
118 }
119
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000122 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000124 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000127 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinVAStart(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 case Builtin::BI__builtin_isgreater:
133 case Builtin::BI__builtin_isgreaterequal:
134 case Builtin::BI__builtin_isless:
135 case Builtin::BI__builtin_islessequal:
136 case Builtin::BI__builtin_islessgreater:
137 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinUnorderedCompare(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000141 case Builtin::BI__builtin_fpclassify:
142 if (SemaBuiltinFPClassification(TheCall, 6))
143 return ExprError();
144 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000145 case Builtin::BI__builtin_isfinite:
146 case Builtin::BI__builtin_isinf:
147 case Builtin::BI__builtin_isinf_sign:
148 case Builtin::BI__builtin_isnan:
149 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000150 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 return ExprError();
152 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000153 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 return SemaBuiltinShuffleVector(TheCall);
155 // TheCall will be freed by the smart pointer here, but that's fine, since
156 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000157 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinPrefetch(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000161 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 if (SemaBuiltinObjectSize(TheCall))
163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000165 case Builtin::BI__builtin_longjmp:
166 if (SemaBuiltinLongjmp(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000169
170 case Builtin::BI__builtin_classify_type:
171 if (checkArgCount(*this, TheCall, 1)) return true;
172 TheCall->setType(Context.IntTy);
173 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000174 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000175 if (checkArgCount(*this, TheCall, 1)) return true;
176 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000177 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000178 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000179 case Builtin::BI__sync_fetch_and_add_1:
180 case Builtin::BI__sync_fetch_and_add_2:
181 case Builtin::BI__sync_fetch_and_add_4:
182 case Builtin::BI__sync_fetch_and_add_8:
183 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000184 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000185 case Builtin::BI__sync_fetch_and_sub_1:
186 case Builtin::BI__sync_fetch_and_sub_2:
187 case Builtin::BI__sync_fetch_and_sub_4:
188 case Builtin::BI__sync_fetch_and_sub_8:
189 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000190 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000191 case Builtin::BI__sync_fetch_and_or_1:
192 case Builtin::BI__sync_fetch_and_or_2:
193 case Builtin::BI__sync_fetch_and_or_4:
194 case Builtin::BI__sync_fetch_and_or_8:
195 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000196 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000197 case Builtin::BI__sync_fetch_and_and_1:
198 case Builtin::BI__sync_fetch_and_and_2:
199 case Builtin::BI__sync_fetch_and_and_4:
200 case Builtin::BI__sync_fetch_and_and_8:
201 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000202 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000203 case Builtin::BI__sync_fetch_and_xor_1:
204 case Builtin::BI__sync_fetch_and_xor_2:
205 case Builtin::BI__sync_fetch_and_xor_4:
206 case Builtin::BI__sync_fetch_and_xor_8:
207 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000208 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000209 case Builtin::BI__sync_add_and_fetch_1:
210 case Builtin::BI__sync_add_and_fetch_2:
211 case Builtin::BI__sync_add_and_fetch_4:
212 case Builtin::BI__sync_add_and_fetch_8:
213 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000215 case Builtin::BI__sync_sub_and_fetch_1:
216 case Builtin::BI__sync_sub_and_fetch_2:
217 case Builtin::BI__sync_sub_and_fetch_4:
218 case Builtin::BI__sync_sub_and_fetch_8:
219 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000220 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000221 case Builtin::BI__sync_and_and_fetch_1:
222 case Builtin::BI__sync_and_and_fetch_2:
223 case Builtin::BI__sync_and_and_fetch_4:
224 case Builtin::BI__sync_and_and_fetch_8:
225 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000226 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000227 case Builtin::BI__sync_or_and_fetch_1:
228 case Builtin::BI__sync_or_and_fetch_2:
229 case Builtin::BI__sync_or_and_fetch_4:
230 case Builtin::BI__sync_or_and_fetch_8:
231 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000232 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000233 case Builtin::BI__sync_xor_and_fetch_1:
234 case Builtin::BI__sync_xor_and_fetch_2:
235 case Builtin::BI__sync_xor_and_fetch_4:
236 case Builtin::BI__sync_xor_and_fetch_8:
237 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000238 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000239 case Builtin::BI__sync_val_compare_and_swap_1:
240 case Builtin::BI__sync_val_compare_and_swap_2:
241 case Builtin::BI__sync_val_compare_and_swap_4:
242 case Builtin::BI__sync_val_compare_and_swap_8:
243 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000244 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000245 case Builtin::BI__sync_bool_compare_and_swap_1:
246 case Builtin::BI__sync_bool_compare_and_swap_2:
247 case Builtin::BI__sync_bool_compare_and_swap_4:
248 case Builtin::BI__sync_bool_compare_and_swap_8:
249 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000250 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000251 case Builtin::BI__sync_lock_test_and_set_1:
252 case Builtin::BI__sync_lock_test_and_set_2:
253 case Builtin::BI__sync_lock_test_and_set_4:
254 case Builtin::BI__sync_lock_test_and_set_8:
255 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000256 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000257 case Builtin::BI__sync_lock_release_1:
258 case Builtin::BI__sync_lock_release_2:
259 case Builtin::BI__sync_lock_release_4:
260 case Builtin::BI__sync_lock_release_8:
261 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000262 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000263 case Builtin::BI__sync_swap_1:
264 case Builtin::BI__sync_swap_2:
265 case Builtin::BI__sync_swap_4:
266 case Builtin::BI__sync_swap_8:
267 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000268 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000272 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000273#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000274 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000275 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 return ExprError();
277 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000278 }
279
280 // Since the target specific builtins for each arch overlap, only check those
281 // of the arch we are compiling for.
282 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000283 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000284 case llvm::Triple::arm:
285 case llvm::Triple::thumb:
286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287 return ExprError();
288 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000289 case llvm::Triple::mips:
290 case llvm::Triple::mipsel:
291 case llvm::Triple::mips64:
292 case llvm::Triple::mips64el:
293 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
294 return ExprError();
295 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000296 default:
297 break;
298 }
299 }
300
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000301 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000302}
303
Nate Begeman61eecf52010-06-14 05:21:25 +0000304// Get the valid immediate range for the specified NEON type code.
305static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000306 NeonTypeFlags Type(t);
307 int IsQuad = Type.isQuad();
308 switch (Type.getEltType()) {
309 case NeonTypeFlags::Int8:
310 case NeonTypeFlags::Poly8:
311 return shift ? 7 : (8 << IsQuad) - 1;
312 case NeonTypeFlags::Int16:
313 case NeonTypeFlags::Poly16:
314 return shift ? 15 : (4 << IsQuad) - 1;
315 case NeonTypeFlags::Int32:
316 return shift ? 31 : (2 << IsQuad) - 1;
317 case NeonTypeFlags::Int64:
318 return shift ? 63 : (1 << IsQuad) - 1;
319 case NeonTypeFlags::Float16:
320 assert(!shift && "cannot shift float types!");
321 return (4 << IsQuad) - 1;
322 case NeonTypeFlags::Float32:
323 assert(!shift && "cannot shift float types!");
324 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000325 }
David Blaikie7530c032012-01-17 06:56:22 +0000326 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000327}
328
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000329/// getNeonEltType - Return the QualType corresponding to the elements of
330/// the vector type specified by the NeonTypeFlags. This is used to check
331/// the pointer arguments for Neon load/store intrinsics.
332static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
333 switch (Flags.getEltType()) {
334 case NeonTypeFlags::Int8:
335 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
336 case NeonTypeFlags::Int16:
337 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
338 case NeonTypeFlags::Int32:
339 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
340 case NeonTypeFlags::Int64:
341 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
342 case NeonTypeFlags::Poly8:
343 return Context.SignedCharTy;
344 case NeonTypeFlags::Poly16:
345 return Context.ShortTy;
346 case NeonTypeFlags::Float16:
347 return Context.UnsignedShortTy;
348 case NeonTypeFlags::Float32:
349 return Context.FloatTy;
350 }
David Blaikie7530c032012-01-17 06:56:22 +0000351 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000352}
353
Nate Begeman26a31422010-06-08 02:47:44 +0000354bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000355 llvm::APSInt Result;
356
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000357 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000358 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000359 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000360 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000361 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000362#define GET_NEON_OVERLOAD_CHECK
363#include "clang/Basic/arm_neon.inc"
364#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000365 }
366
Nate Begeman0d15c532010-06-13 04:47:52 +0000367 // For NEON intrinsics which are overloaded on vector element type, validate
368 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000369 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000370 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000371 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000372 return true;
373
Bob Wilsonda95f732011-11-08 01:16:11 +0000374 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000375 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000376 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 << TheCall->getArg(ImmArg)->getSourceRange();
378 }
379
Bob Wilson46482552011-11-16 21:32:23 +0000380 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000382 Expr *Arg = TheCall->getArg(PtrArgNum);
383 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
384 Arg = ICE->getSubExpr();
385 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
386 QualType RHSTy = RHS.get()->getType();
387 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
388 if (HasConstPtr)
389 EltTy = EltTy.withConst();
390 QualType LHSTy = Context.getPointerType(EltTy);
391 AssignConvertType ConvTy;
392 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
393 if (RHS.isInvalid())
394 return true;
395 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
396 RHS.get(), AA_Assigning))
397 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000398 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000399
Nate Begeman0d15c532010-06-13 04:47:52 +0000400 // For NEON intrinsics which take an immediate value as part of the
401 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000402 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000403 switch (BuiltinID) {
404 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000405 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
406 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000407 case ARM::BI__builtin_arm_vcvtr_f:
408 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000409#define GET_NEON_IMMEDIATE_CHECK
410#include "clang/Basic/arm_neon.inc"
411#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000412 };
413
Douglas Gregor592a4232012-06-29 01:05:22 +0000414 // We can't check the value of a dependent argument.
415 if (TheCall->getArg(i)->isTypeDependent() ||
416 TheCall->getArg(i)->isValueDependent())
417 return false;
418
Nate Begeman61eecf52010-06-14 05:21:25 +0000419 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 if (SemaBuiltinConstantArg(TheCall, i, Result))
421 return true;
422
Nate Begeman61eecf52010-06-14 05:21:25 +0000423 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000424 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000425 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000426 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000427 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000428
Nate Begeman99c40bb2010-08-03 21:32:34 +0000429 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000430 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000431}
Daniel Dunbarde454282008-10-02 18:44:07 +0000432
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000433bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
434 unsigned i = 0, l = 0, u = 0;
435 switch (BuiltinID) {
436 default: return false;
437 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
438 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000439 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
440 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
441 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
442 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000444 };
445
446 // We can't check the value of a dependent argument.
447 if (TheCall->getArg(i)->isTypeDependent() ||
448 TheCall->getArg(i)->isValueDependent())
449 return false;
450
451 // Check that the immediate argument is actually a constant.
452 llvm::APSInt Result;
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
454 return true;
455
456 // Range check against the upper/lower values for this instruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > u)
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u << TheCall->getArg(i)->getSourceRange();
461
462 return false;
463}
464
Richard Smith831421f2012-06-25 20:30:08 +0000465/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
466/// parameter with the FormatAttr's correct format_idx and firstDataArg.
467/// Returns true when the format fits the function and the FormatStringInfo has
468/// been populated.
469bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
470 FormatStringInfo *FSI) {
471 FSI->HasVAListArg = Format->getFirstArg() == 0;
472 FSI->FormatIdx = Format->getFormatIdx() - 1;
473 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000474
Richard Smith831421f2012-06-25 20:30:08 +0000475 // The way the format attribute works in GCC, the implicit this argument
476 // of member functions is counted. However, it doesn't appear in our own
477 // lists, so decrement format_idx in that case.
478 if (IsCXXMember) {
479 if(FSI->FormatIdx == 0)
480 return false;
481 --FSI->FormatIdx;
482 if (FSI->FirstDataArg != 0)
483 --FSI->FirstDataArg;
484 }
485 return true;
486}
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Richard Smith831421f2012-06-25 20:30:08 +0000488/// Handles the checks for format strings, non-POD arguments to vararg
489/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000490void Sema::checkCall(NamedDecl *FDecl,
491 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000492 unsigned NumProtoArgs,
493 bool IsMemberFunction,
494 SourceLocation Loc,
495 SourceRange Range,
496 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000497 if (CurContext->isDependentContext())
498 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000499
Ted Kremenekc82faca2010-09-09 04:33:05 +0000500 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000501 bool HandledFormatString = false;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000502 if (FDecl)
503 for (specific_attr_iterator<FormatAttr>
504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
506 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc,
507 Range))
508 HandledFormatString = true;
Richard Smith831421f2012-06-25 20:30:08 +0000509
510 // Refuse POD arguments that weren't caught by the format string
511 // checks above.
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000514 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000515 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000516 variadicArgumentPODCheck(Arg, CallType);
517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Richard Trieu0538f0e2013-06-22 00:20:41 +0000519 if (FDecl) {
520 for (specific_attr_iterator<NonNullAttr>
521 I = FDecl->specific_attr_begin<NonNullAttr>(),
522 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
523 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000524
Richard Trieu0538f0e2013-06-22 00:20:41 +0000525 // Type safety checking.
526 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
527 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
528 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
529 i != e; ++i) {
530 CheckArgumentWithTypeTag(*i, Args.data());
531 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000532 }
Richard Smith831421f2012-06-25 20:30:08 +0000533}
534
535/// CheckConstructorCall - Check a constructor call for correctness and safety
536/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000537void Sema::CheckConstructorCall(FunctionDecl *FDecl,
538 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000539 const FunctionProtoType *Proto,
540 SourceLocation Loc) {
541 VariadicCallType CallType =
542 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000543 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000544 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
545}
546
547/// CheckFunctionCall - Check a direct function call for various correctness
548/// and safety properties not strictly enforced by the C type system.
549bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
550 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000551 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
552 isa<CXXMethodDecl>(FDecl);
553 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
554 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000555 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
556 TheCall->getCallee());
557 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000558 Expr** Args = TheCall->getArgs();
559 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000560 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000561 // If this is a call to a member operator, hide the first argument
562 // from checkCall.
563 // FIXME: Our choice of AST representation here is less than ideal.
564 ++Args;
565 --NumArgs;
566 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000567 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
568 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000569 IsMemberFunction, TheCall->getRParenLoc(),
570 TheCall->getCallee()->getSourceRange(), CallType);
571
572 IdentifierInfo *FnInfo = FDecl->getIdentifier();
573 // None of the checks below are needed for functions that don't have
574 // simple names (e.g., C++ conversion functions).
575 if (!FnInfo)
576 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000577
Anna Zaks0a151a12012-01-17 00:37:07 +0000578 unsigned CMId = FDecl->getMemoryFunctionKind();
579 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000580 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000581
Anna Zaksd9b859a2012-01-13 21:52:01 +0000582 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000583 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000584 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000585 else if (CMId == Builtin::BIstrncat)
586 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000587 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000588 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000589
Anders Carlssond406bf02009-08-16 01:56:34 +0000590 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000591}
592
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000593bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000594 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000595 VariadicCallType CallType =
596 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000597
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000598 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000599 /*IsMemberFunction=*/false,
600 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000601
602 return false;
603}
604
Richard Trieuf462b012013-06-20 21:03:13 +0000605bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
606 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
608 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000611 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000612 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000613 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Richard Trieuf462b012013-06-20 21:03:13 +0000615 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000616 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000617 CallType = VariadicDoesNotApply;
618 } else if (Ty->isBlockPointerType()) {
619 CallType = VariadicBlock;
620 } else { // Ty->isFunctionPointerType()
621 CallType = VariadicFunction;
622 }
Richard Smith831421f2012-06-25 20:30:08 +0000623 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000624
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000625 checkCall(NDecl,
626 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
627 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000628 NumProtoArgs, /*IsMemberFunction=*/false,
629 TheCall->getRParenLoc(),
630 TheCall->getCallee()->getSourceRange(), CallType);
631
Anders Carlssond406bf02009-08-16 01:56:34 +0000632 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000633}
634
Richard Trieu0538f0e2013-06-22 00:20:41 +0000635/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
636/// such as function pointers returned from functions.
637bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
638 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
639 TheCall->getCallee());
640 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
641
642 checkCall(/*FDecl=*/0,
643 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
644 TheCall->getNumArgs()),
645 NumProtoArgs, /*IsMemberFunction=*/false,
646 TheCall->getRParenLoc(),
647 TheCall->getCallee()->getSourceRange(), CallType);
648
649 return false;
650}
651
Richard Smithff34d402012-04-12 05:08:17 +0000652ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
653 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000654 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
655 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000656
Richard Smithff34d402012-04-12 05:08:17 +0000657 // All these operations take one of the following forms:
658 enum {
659 // C __c11_atomic_init(A *, C)
660 Init,
661 // C __c11_atomic_load(A *, int)
662 Load,
663 // void __atomic_load(A *, CP, int)
664 Copy,
665 // C __c11_atomic_add(A *, M, int)
666 Arithmetic,
667 // C __atomic_exchange_n(A *, CP, int)
668 Xchg,
669 // void __atomic_exchange(A *, C *, CP, int)
670 GNUXchg,
671 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
672 C11CmpXchg,
673 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
674 GNUCmpXchg
675 } Form = Init;
676 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
677 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
678 // where:
679 // C is an appropriate type,
680 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
681 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
682 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
683 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000684
Richard Smithff34d402012-04-12 05:08:17 +0000685 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
686 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
687 && "need to update code for modified C11 atomics");
688 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
689 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
690 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
691 Op == AtomicExpr::AO__atomic_store_n ||
692 Op == AtomicExpr::AO__atomic_exchange_n ||
693 Op == AtomicExpr::AO__atomic_compare_exchange_n;
694 bool IsAddSub = false;
695
696 switch (Op) {
697 case AtomicExpr::AO__c11_atomic_init:
698 Form = Init;
699 break;
700
701 case AtomicExpr::AO__c11_atomic_load:
702 case AtomicExpr::AO__atomic_load_n:
703 Form = Load;
704 break;
705
706 case AtomicExpr::AO__c11_atomic_store:
707 case AtomicExpr::AO__atomic_load:
708 case AtomicExpr::AO__atomic_store:
709 case AtomicExpr::AO__atomic_store_n:
710 Form = Copy;
711 break;
712
713 case AtomicExpr::AO__c11_atomic_fetch_add:
714 case AtomicExpr::AO__c11_atomic_fetch_sub:
715 case AtomicExpr::AO__atomic_fetch_add:
716 case AtomicExpr::AO__atomic_fetch_sub:
717 case AtomicExpr::AO__atomic_add_fetch:
718 case AtomicExpr::AO__atomic_sub_fetch:
719 IsAddSub = true;
720 // Fall through.
721 case AtomicExpr::AO__c11_atomic_fetch_and:
722 case AtomicExpr::AO__c11_atomic_fetch_or:
723 case AtomicExpr::AO__c11_atomic_fetch_xor:
724 case AtomicExpr::AO__atomic_fetch_and:
725 case AtomicExpr::AO__atomic_fetch_or:
726 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000727 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000728 case AtomicExpr::AO__atomic_and_fetch:
729 case AtomicExpr::AO__atomic_or_fetch:
730 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000731 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000732 Form = Arithmetic;
733 break;
734
735 case AtomicExpr::AO__c11_atomic_exchange:
736 case AtomicExpr::AO__atomic_exchange_n:
737 Form = Xchg;
738 break;
739
740 case AtomicExpr::AO__atomic_exchange:
741 Form = GNUXchg;
742 break;
743
744 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
745 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
746 Form = C11CmpXchg;
747 break;
748
749 case AtomicExpr::AO__atomic_compare_exchange:
750 case AtomicExpr::AO__atomic_compare_exchange_n:
751 Form = GNUCmpXchg;
752 break;
753 }
754
755 // Check we have the right number of arguments.
756 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000757 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000758 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000759 << TheCall->getCallee()->getSourceRange();
760 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000761 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
762 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000763 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000764 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000765 << TheCall->getCallee()->getSourceRange();
766 return ExprError();
767 }
768
Richard Smithff34d402012-04-12 05:08:17 +0000769 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000770 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000771 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
772 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
773 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000774 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000775 << Ptr->getType() << Ptr->getSourceRange();
776 return ExprError();
777 }
778
Richard Smithff34d402012-04-12 05:08:17 +0000779 // For a __c11 builtin, this should be a pointer to an _Atomic type.
780 QualType AtomTy = pointerType->getPointeeType(); // 'A'
781 QualType ValType = AtomTy; // 'C'
782 if (IsC11) {
783 if (!AtomTy->isAtomicType()) {
784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
785 << Ptr->getType() << Ptr->getSourceRange();
786 return ExprError();
787 }
Richard Smithbc57b102012-09-15 06:09:58 +0000788 if (AtomTy.isConstQualified()) {
789 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
790 << Ptr->getType() << Ptr->getSourceRange();
791 return ExprError();
792 }
Richard Smithff34d402012-04-12 05:08:17 +0000793 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000794 }
Eli Friedman276b0612011-10-11 02:20:01 +0000795
Richard Smithff34d402012-04-12 05:08:17 +0000796 // For an arithmetic operation, the implied arithmetic must be well-formed.
797 if (Form == Arithmetic) {
798 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
799 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
800 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
801 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
802 return ExprError();
803 }
804 if (!IsAddSub && !ValType->isIntegerType()) {
805 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
806 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
807 return ExprError();
808 }
809 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
810 // For __atomic_*_n operations, the value type must be a scalar integral or
811 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000812 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000813 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
814 return ExprError();
815 }
816
817 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
818 // For GNU atomics, require a trivially-copyable type. This is not part of
819 // the GNU atomics specification, but we enforce it for sanity.
820 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000821 << Ptr->getType() << Ptr->getSourceRange();
822 return ExprError();
823 }
824
Richard Smithff34d402012-04-12 05:08:17 +0000825 // FIXME: For any builtin other than a load, the ValType must not be
826 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000827
828 switch (ValType.getObjCLifetime()) {
829 case Qualifiers::OCL_None:
830 case Qualifiers::OCL_ExplicitNone:
831 // okay
832 break;
833
834 case Qualifiers::OCL_Weak:
835 case Qualifiers::OCL_Strong:
836 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000837 // FIXME: Can this happen? By this point, ValType should be known
838 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000839 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
840 << ValType << Ptr->getSourceRange();
841 return ExprError();
842 }
843
844 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000845 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000846 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000847 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000848 ResultType = Context.BoolTy;
849
Richard Smithff34d402012-04-12 05:08:17 +0000850 // The type of a parameter passed 'by value'. In the GNU atomics, such
851 // arguments are actually passed as pointers.
852 QualType ByValType = ValType; // 'CP'
853 if (!IsC11 && !IsN)
854 ByValType = Ptr->getType();
855
Eli Friedman276b0612011-10-11 02:20:01 +0000856 // The first argument --- the pointer --- has a fixed type; we
857 // deduce the types of the rest of the arguments accordingly. Walk
858 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000859 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000860 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000861 if (i < NumVals[Form] + 1) {
862 switch (i) {
863 case 1:
864 // The second argument is the non-atomic operand. For arithmetic, this
865 // is always passed by value, and for a compare_exchange it is always
866 // passed by address. For the rest, GNU uses by-address and C11 uses
867 // by-value.
868 assert(Form != Load);
869 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
870 Ty = ValType;
871 else if (Form == Copy || Form == Xchg)
872 Ty = ByValType;
873 else if (Form == Arithmetic)
874 Ty = Context.getPointerDiffType();
875 else
876 Ty = Context.getPointerType(ValType.getUnqualifiedType());
877 break;
878 case 2:
879 // The third argument to compare_exchange / GNU exchange is a
880 // (pointer to a) desired value.
881 Ty = ByValType;
882 break;
883 case 3:
884 // The fourth argument to GNU compare_exchange is a 'weak' flag.
885 Ty = Context.BoolTy;
886 break;
887 }
Eli Friedman276b0612011-10-11 02:20:01 +0000888 } else {
889 // The order(s) are always converted to int.
890 Ty = Context.IntTy;
891 }
Richard Smithff34d402012-04-12 05:08:17 +0000892
Eli Friedman276b0612011-10-11 02:20:01 +0000893 InitializedEntity Entity =
894 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000895 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000896 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
897 if (Arg.isInvalid())
898 return true;
899 TheCall->setArg(i, Arg.get());
900 }
901
Richard Smithff34d402012-04-12 05:08:17 +0000902 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000903 SmallVector<Expr*, 5> SubExprs;
904 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000905 switch (Form) {
906 case Init:
907 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000908 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000909 break;
910 case Load:
911 SubExprs.push_back(TheCall->getArg(1)); // Order
912 break;
913 case Copy:
914 case Arithmetic:
915 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000916 SubExprs.push_back(TheCall->getArg(2)); // Order
917 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000918 break;
919 case GNUXchg:
920 // Note, AtomicExpr::getVal2() has a special case for this atomic.
921 SubExprs.push_back(TheCall->getArg(3)); // Order
922 SubExprs.push_back(TheCall->getArg(1)); // Val1
923 SubExprs.push_back(TheCall->getArg(2)); // Val2
924 break;
925 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000926 SubExprs.push_back(TheCall->getArg(3)); // Order
927 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000928 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000929 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000930 break;
931 case GNUCmpXchg:
932 SubExprs.push_back(TheCall->getArg(4)); // Order
933 SubExprs.push_back(TheCall->getArg(1)); // Val1
934 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
935 SubExprs.push_back(TheCall->getArg(2)); // Val2
936 SubExprs.push_back(TheCall->getArg(3)); // Weak
937 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000938 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000939
940 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
941 SubExprs, ResultType, Op,
942 TheCall->getRParenLoc());
943
944 if ((Op == AtomicExpr::AO__c11_atomic_load ||
945 (Op == AtomicExpr::AO__c11_atomic_store)) &&
946 Context.AtomicUsesUnsupportedLibcall(AE))
947 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
948 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000949
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000950 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +0000951}
952
953
John McCall5f8d6042011-08-27 01:09:30 +0000954/// checkBuiltinArgument - Given a call to a builtin function, perform
955/// normal type-checking on the given argument, updating the call in
956/// place. This is useful when a builtin function requires custom
957/// type-checking for some of its arguments but not necessarily all of
958/// them.
959///
960/// Returns true on error.
961static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
962 FunctionDecl *Fn = E->getDirectCallee();
963 assert(Fn && "builtin call without direct callee!");
964
965 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
966 InitializedEntity Entity =
967 InitializedEntity::InitializeParameter(S.Context, Param);
968
969 ExprResult Arg = E->getArg(0);
970 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
971 if (Arg.isInvalid())
972 return true;
973
974 E->setArg(ArgIndex, Arg.take());
975 return false;
976}
977
Chris Lattner5caa3702009-05-08 06:58:22 +0000978/// SemaBuiltinAtomicOverloaded - We have a call to a function like
979/// __sync_fetch_and_add, which is an overloaded function based on the pointer
980/// type of its first argument. The main ActOnCallExpr routines have already
981/// promoted the types of arguments because all of these calls are prototyped as
982/// void(...).
983///
984/// This function goes through and does final semantic checking for these
985/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000986ExprResult
987Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000988 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000989 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
990 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
991
992 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000993 if (TheCall->getNumArgs() < 1) {
994 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
995 << 0 << 1 << TheCall->getNumArgs()
996 << TheCall->getCallee()->getSourceRange();
997 return ExprError();
998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner5caa3702009-05-08 06:58:22 +00001000 // Inspect the first argument of the atomic builtin. This should always be
1001 // a pointer type, whose element is an integral scalar or pointer type.
1002 // Because it is a pointer type, we don't have to worry about any implicit
1003 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001004 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001005 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001006 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1007 if (FirstArgResult.isInvalid())
1008 return ExprError();
1009 FirstArg = FirstArgResult.take();
1010 TheCall->setArg(0, FirstArg);
1011
John McCallf85e1932011-06-15 23:02:42 +00001012 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1013 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001014 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1015 << FirstArg->getType() << FirstArg->getSourceRange();
1016 return ExprError();
1017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
John McCallf85e1932011-06-15 23:02:42 +00001019 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001020 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001021 !ValType->isBlockPointerType()) {
1022 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1023 << FirstArg->getType() << FirstArg->getSourceRange();
1024 return ExprError();
1025 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001026
John McCallf85e1932011-06-15 23:02:42 +00001027 switch (ValType.getObjCLifetime()) {
1028 case Qualifiers::OCL_None:
1029 case Qualifiers::OCL_ExplicitNone:
1030 // okay
1031 break;
1032
1033 case Qualifiers::OCL_Weak:
1034 case Qualifiers::OCL_Strong:
1035 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001036 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001037 << ValType << FirstArg->getSourceRange();
1038 return ExprError();
1039 }
1040
John McCallb45ae252011-10-05 07:41:44 +00001041 // Strip any qualifiers off ValType.
1042 ValType = ValType.getUnqualifiedType();
1043
Chandler Carruth8d13d222010-07-18 20:54:12 +00001044 // The majority of builtins return a value, but a few have special return
1045 // types, so allow them to override appropriately below.
1046 QualType ResultType = ValType;
1047
Chris Lattner5caa3702009-05-08 06:58:22 +00001048 // We need to figure out which concrete builtin this maps onto. For example,
1049 // __sync_fetch_and_add with a 2 byte object turns into
1050 // __sync_fetch_and_add_2.
1051#define BUILTIN_ROW(x) \
1052 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1053 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner5caa3702009-05-08 06:58:22 +00001055 static const unsigned BuiltinIndices[][5] = {
1056 BUILTIN_ROW(__sync_fetch_and_add),
1057 BUILTIN_ROW(__sync_fetch_and_sub),
1058 BUILTIN_ROW(__sync_fetch_and_or),
1059 BUILTIN_ROW(__sync_fetch_and_and),
1060 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner5caa3702009-05-08 06:58:22 +00001062 BUILTIN_ROW(__sync_add_and_fetch),
1063 BUILTIN_ROW(__sync_sub_and_fetch),
1064 BUILTIN_ROW(__sync_and_and_fetch),
1065 BUILTIN_ROW(__sync_or_and_fetch),
1066 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner5caa3702009-05-08 06:58:22 +00001068 BUILTIN_ROW(__sync_val_compare_and_swap),
1069 BUILTIN_ROW(__sync_bool_compare_and_swap),
1070 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001071 BUILTIN_ROW(__sync_lock_release),
1072 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001073 };
Mike Stump1eb44332009-09-09 15:08:12 +00001074#undef BUILTIN_ROW
1075
Chris Lattner5caa3702009-05-08 06:58:22 +00001076 // Determine the index of the size.
1077 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001078 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001079 case 1: SizeIndex = 0; break;
1080 case 2: SizeIndex = 1; break;
1081 case 4: SizeIndex = 2; break;
1082 case 8: SizeIndex = 3; break;
1083 case 16: SizeIndex = 4; break;
1084 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001085 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1086 << FirstArg->getType() << FirstArg->getSourceRange();
1087 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Chris Lattner5caa3702009-05-08 06:58:22 +00001090 // Each of these builtins has one pointer argument, followed by some number of
1091 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1092 // that we ignore. Find out which row of BuiltinIndices to read from as well
1093 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001094 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001095 unsigned BuiltinIndex, NumFixed = 1;
1096 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001097 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001098 case Builtin::BI__sync_fetch_and_add:
1099 case Builtin::BI__sync_fetch_and_add_1:
1100 case Builtin::BI__sync_fetch_and_add_2:
1101 case Builtin::BI__sync_fetch_and_add_4:
1102 case Builtin::BI__sync_fetch_and_add_8:
1103 case Builtin::BI__sync_fetch_and_add_16:
1104 BuiltinIndex = 0;
1105 break;
1106
1107 case Builtin::BI__sync_fetch_and_sub:
1108 case Builtin::BI__sync_fetch_and_sub_1:
1109 case Builtin::BI__sync_fetch_and_sub_2:
1110 case Builtin::BI__sync_fetch_and_sub_4:
1111 case Builtin::BI__sync_fetch_and_sub_8:
1112 case Builtin::BI__sync_fetch_and_sub_16:
1113 BuiltinIndex = 1;
1114 break;
1115
1116 case Builtin::BI__sync_fetch_and_or:
1117 case Builtin::BI__sync_fetch_and_or_1:
1118 case Builtin::BI__sync_fetch_and_or_2:
1119 case Builtin::BI__sync_fetch_and_or_4:
1120 case Builtin::BI__sync_fetch_and_or_8:
1121 case Builtin::BI__sync_fetch_and_or_16:
1122 BuiltinIndex = 2;
1123 break;
1124
1125 case Builtin::BI__sync_fetch_and_and:
1126 case Builtin::BI__sync_fetch_and_and_1:
1127 case Builtin::BI__sync_fetch_and_and_2:
1128 case Builtin::BI__sync_fetch_and_and_4:
1129 case Builtin::BI__sync_fetch_and_and_8:
1130 case Builtin::BI__sync_fetch_and_and_16:
1131 BuiltinIndex = 3;
1132 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregora9766412011-11-28 16:30:08 +00001134 case Builtin::BI__sync_fetch_and_xor:
1135 case Builtin::BI__sync_fetch_and_xor_1:
1136 case Builtin::BI__sync_fetch_and_xor_2:
1137 case Builtin::BI__sync_fetch_and_xor_4:
1138 case Builtin::BI__sync_fetch_and_xor_8:
1139 case Builtin::BI__sync_fetch_and_xor_16:
1140 BuiltinIndex = 4;
1141 break;
1142
1143 case Builtin::BI__sync_add_and_fetch:
1144 case Builtin::BI__sync_add_and_fetch_1:
1145 case Builtin::BI__sync_add_and_fetch_2:
1146 case Builtin::BI__sync_add_and_fetch_4:
1147 case Builtin::BI__sync_add_and_fetch_8:
1148 case Builtin::BI__sync_add_and_fetch_16:
1149 BuiltinIndex = 5;
1150 break;
1151
1152 case Builtin::BI__sync_sub_and_fetch:
1153 case Builtin::BI__sync_sub_and_fetch_1:
1154 case Builtin::BI__sync_sub_and_fetch_2:
1155 case Builtin::BI__sync_sub_and_fetch_4:
1156 case Builtin::BI__sync_sub_and_fetch_8:
1157 case Builtin::BI__sync_sub_and_fetch_16:
1158 BuiltinIndex = 6;
1159 break;
1160
1161 case Builtin::BI__sync_and_and_fetch:
1162 case Builtin::BI__sync_and_and_fetch_1:
1163 case Builtin::BI__sync_and_and_fetch_2:
1164 case Builtin::BI__sync_and_and_fetch_4:
1165 case Builtin::BI__sync_and_and_fetch_8:
1166 case Builtin::BI__sync_and_and_fetch_16:
1167 BuiltinIndex = 7;
1168 break;
1169
1170 case Builtin::BI__sync_or_and_fetch:
1171 case Builtin::BI__sync_or_and_fetch_1:
1172 case Builtin::BI__sync_or_and_fetch_2:
1173 case Builtin::BI__sync_or_and_fetch_4:
1174 case Builtin::BI__sync_or_and_fetch_8:
1175 case Builtin::BI__sync_or_and_fetch_16:
1176 BuiltinIndex = 8;
1177 break;
1178
1179 case Builtin::BI__sync_xor_and_fetch:
1180 case Builtin::BI__sync_xor_and_fetch_1:
1181 case Builtin::BI__sync_xor_and_fetch_2:
1182 case Builtin::BI__sync_xor_and_fetch_4:
1183 case Builtin::BI__sync_xor_and_fetch_8:
1184 case Builtin::BI__sync_xor_and_fetch_16:
1185 BuiltinIndex = 9;
1186 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Chris Lattner5caa3702009-05-08 06:58:22 +00001188 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001189 case Builtin::BI__sync_val_compare_and_swap_1:
1190 case Builtin::BI__sync_val_compare_and_swap_2:
1191 case Builtin::BI__sync_val_compare_and_swap_4:
1192 case Builtin::BI__sync_val_compare_and_swap_8:
1193 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001194 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001195 NumFixed = 2;
1196 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001197
Chris Lattner5caa3702009-05-08 06:58:22 +00001198 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001199 case Builtin::BI__sync_bool_compare_and_swap_1:
1200 case Builtin::BI__sync_bool_compare_and_swap_2:
1201 case Builtin::BI__sync_bool_compare_and_swap_4:
1202 case Builtin::BI__sync_bool_compare_and_swap_8:
1203 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001204 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001205 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001206 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001207 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001208
1209 case Builtin::BI__sync_lock_test_and_set:
1210 case Builtin::BI__sync_lock_test_and_set_1:
1211 case Builtin::BI__sync_lock_test_and_set_2:
1212 case Builtin::BI__sync_lock_test_and_set_4:
1213 case Builtin::BI__sync_lock_test_and_set_8:
1214 case Builtin::BI__sync_lock_test_and_set_16:
1215 BuiltinIndex = 12;
1216 break;
1217
Chris Lattner5caa3702009-05-08 06:58:22 +00001218 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001219 case Builtin::BI__sync_lock_release_1:
1220 case Builtin::BI__sync_lock_release_2:
1221 case Builtin::BI__sync_lock_release_4:
1222 case Builtin::BI__sync_lock_release_8:
1223 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001224 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001225 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001226 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001227 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001228
1229 case Builtin::BI__sync_swap:
1230 case Builtin::BI__sync_swap_1:
1231 case Builtin::BI__sync_swap_2:
1232 case Builtin::BI__sync_swap_4:
1233 case Builtin::BI__sync_swap_8:
1234 case Builtin::BI__sync_swap_16:
1235 BuiltinIndex = 14;
1236 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner5caa3702009-05-08 06:58:22 +00001239 // Now that we know how many fixed arguments we expect, first check that we
1240 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001241 if (TheCall->getNumArgs() < 1+NumFixed) {
1242 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1243 << 0 << 1+NumFixed << TheCall->getNumArgs()
1244 << TheCall->getCallee()->getSourceRange();
1245 return ExprError();
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001248 // Get the decl for the concrete builtin from this, we can tell what the
1249 // concrete integer type we should convert to is.
1250 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1251 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001252 FunctionDecl *NewBuiltinDecl;
1253 if (NewBuiltinID == BuiltinID)
1254 NewBuiltinDecl = FDecl;
1255 else {
1256 // Perform builtin lookup to avoid redeclaring it.
1257 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1258 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1259 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1260 assert(Res.getFoundDecl());
1261 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1262 if (NewBuiltinDecl == 0)
1263 return ExprError();
1264 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001265
John McCallf871d0c2010-08-07 06:22:56 +00001266 // The first argument --- the pointer --- has a fixed type; we
1267 // deduce the types of the rest of the arguments accordingly. Walk
1268 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001269 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001270 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner5caa3702009-05-08 06:58:22 +00001272 // GCC does an implicit conversion to the pointer or integer ValType. This
1273 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001274 // Initialize the argument.
1275 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1276 ValType, /*consume*/ false);
1277 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001278 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001279 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Chris Lattner5caa3702009-05-08 06:58:22 +00001281 // Okay, we have something that *can* be converted to the right type. Check
1282 // to see if there is a potentially weird extension going on here. This can
1283 // happen when you do an atomic operation on something like an char* and
1284 // pass in 42. The 42 gets converted to char. This is even more strange
1285 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001286 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001287 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001288 }
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001290 ASTContext& Context = this->getASTContext();
1291
1292 // Create a new DeclRefExpr to refer to the new decl.
1293 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1294 Context,
1295 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001296 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001297 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001298 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001299 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001300 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001301 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Chris Lattner5caa3702009-05-08 06:58:22 +00001303 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001304 // FIXME: This loses syntactic information.
1305 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1306 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1307 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001308 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001310 // Change the result type of the call to match the original value type. This
1311 // is arbitrary, but the codegen for these builtins ins design to handle it
1312 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001313 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001314
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001315 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001316}
1317
Chris Lattner69039812009-02-18 06:01:06 +00001318/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001319/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001320/// Note: It might also make sense to do the UTF-16 conversion here (would
1321/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001322bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001323 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001324 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1325
Douglas Gregor5cee1192011-07-27 05:40:30 +00001326 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001327 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1328 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001329 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001332 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001333 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001334 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001335 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001336 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001337 UTF16 *ToPtr = &ToBuf[0];
1338
1339 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1340 &ToPtr, ToPtr + NumBytes,
1341 strictConversion);
1342 // Check for conversion failure.
1343 if (Result != conversionOK)
1344 Diag(Arg->getLocStart(),
1345 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1346 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001347 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001348}
1349
Chris Lattnerc27c6652007-12-20 00:05:45 +00001350/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1351/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001352bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1353 Expr *Fn = TheCall->getCallee();
1354 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001355 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001356 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001357 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1358 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001359 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001360 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001361 return true;
1362 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001363
1364 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001365 return Diag(TheCall->getLocEnd(),
1366 diag::err_typecheck_call_too_few_args_at_least)
1367 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001368 }
1369
John McCall5f8d6042011-08-27 01:09:30 +00001370 // Type-check the first argument normally.
1371 if (checkBuiltinArgument(*this, TheCall, 0))
1372 return true;
1373
Chris Lattnerc27c6652007-12-20 00:05:45 +00001374 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001375 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001376 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001377 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001378 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001379 else if (FunctionDecl *FD = getCurFunctionDecl())
1380 isVariadic = FD->isVariadic();
1381 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001382 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Chris Lattnerc27c6652007-12-20 00:05:45 +00001384 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001385 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1386 return true;
1387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner30ce3442007-12-19 23:59:04 +00001389 // Verify that the second argument to the builtin is the last argument of the
1390 // current function or method.
1391 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001392 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Nico Weberb07d4482013-05-24 23:31:57 +00001394 // These are valid if SecondArgIsLastNamedArgument is false after the next
1395 // block.
1396 QualType Type;
1397 SourceLocation ParamLoc;
1398
Anders Carlsson88cf2262008-02-11 04:20:54 +00001399 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1400 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001401 // FIXME: This isn't correct for methods (results in bogus warning).
1402 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001403 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001404 if (CurBlock)
1405 LastArg = *(CurBlock->TheDecl->param_end()-1);
1406 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001407 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001408 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001409 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001410 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001411
1412 Type = PV->getType();
1413 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001414 }
1415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner30ce3442007-12-19 23:59:04 +00001417 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001419 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001420 else if (Type->isReferenceType()) {
1421 Diag(Arg->getLocStart(),
1422 diag::warn_va_start_of_reference_type_is_undefined);
1423 Diag(ParamLoc, diag::note_parameter_type) << Type;
1424 }
1425
Chris Lattner30ce3442007-12-19 23:59:04 +00001426 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001427}
Chris Lattner30ce3442007-12-19 23:59:04 +00001428
Chris Lattner1b9a0792007-12-20 00:26:33 +00001429/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1430/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001431bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1432 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001433 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001434 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001435 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001436 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001437 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001438 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001439 << SourceRange(TheCall->getArg(2)->getLocStart(),
1440 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001441
John Wiegley429bb272011-04-08 18:41:53 +00001442 ExprResult OrigArg0 = TheCall->getArg(0);
1443 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001444
Chris Lattner1b9a0792007-12-20 00:26:33 +00001445 // Do standard promotions between the two arguments, returning their common
1446 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001447 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001448 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1449 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001450
1451 // Make sure any conversions are pushed back into the call; this is
1452 // type safe since unordered compare builtins are declared as "_Bool
1453 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001454 TheCall->setArg(0, OrigArg0.get());
1455 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John Wiegley429bb272011-04-08 18:41:53 +00001457 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001458 return false;
1459
Chris Lattner1b9a0792007-12-20 00:26:33 +00001460 // If the common type isn't a real floating type, then the arguments were
1461 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001462 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001463 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001464 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001465 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1466 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner1b9a0792007-12-20 00:26:33 +00001468 return false;
1469}
1470
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001471/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1472/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001473/// to check everything. We expect the last argument to be a floating point
1474/// value.
1475bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1476 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001477 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001478 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001479 if (TheCall->getNumArgs() > NumArgs)
1480 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001481 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001482 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001483 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001484 (*(TheCall->arg_end()-1))->getLocEnd());
1485
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001486 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Eli Friedman9ac6f622009-08-31 20:06:00 +00001488 if (OrigArg->isTypeDependent())
1489 return false;
1490
Chris Lattner81368fb2010-05-06 05:50:07 +00001491 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001492 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001493 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001494 diag::err_typecheck_call_invalid_unary_fp)
1495 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner81368fb2010-05-06 05:50:07 +00001497 // If this is an implicit conversion from float -> double, remove it.
1498 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1499 Expr *CastArg = Cast->getSubExpr();
1500 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1501 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1502 "promotion from float to double is the only expected cast here");
1503 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001504 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001505 }
1506 }
1507
Eli Friedman9ac6f622009-08-31 20:06:00 +00001508 return false;
1509}
1510
Eli Friedmand38617c2008-05-14 19:38:39 +00001511/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1512// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001513ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001514 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001515 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001516 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001517 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001518 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001519
Nate Begeman37b6a572010-06-08 00:16:34 +00001520 // Determine which of the following types of shufflevector we're checking:
1521 // 1) unary, vector mask: (lhs, mask)
1522 // 2) binary, vector mask: (lhs, rhs, mask)
1523 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1524 QualType resType = TheCall->getArg(0)->getType();
1525 unsigned numElements = 0;
1526
Douglas Gregorcde01732009-05-19 22:10:17 +00001527 if (!TheCall->getArg(0)->isTypeDependent() &&
1528 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001529 QualType LHSType = TheCall->getArg(0)->getType();
1530 QualType RHSType = TheCall->getArg(1)->getType();
1531
1532 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001533 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001534 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001535 TheCall->getArg(1)->getLocEnd());
1536 return ExprError();
1537 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001538
1539 numElements = LHSType->getAs<VectorType>()->getNumElements();
1540 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Nate Begeman37b6a572010-06-08 00:16:34 +00001542 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1543 // with mask. If so, verify that RHS is an integer vector type with the
1544 // same number of elts as lhs.
1545 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001546 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001547 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1548 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1549 << SourceRange(TheCall->getArg(1)->getLocStart(),
1550 TheCall->getArg(1)->getLocEnd());
1551 numResElements = numElements;
1552 }
1553 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001554 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001555 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001556 TheCall->getArg(1)->getLocEnd());
1557 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001558 } else if (numElements != numResElements) {
1559 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001560 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001561 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001562 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001563 }
1564
1565 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001566 if (TheCall->getArg(i)->isTypeDependent() ||
1567 TheCall->getArg(i)->isValueDependent())
1568 continue;
1569
Nate Begeman37b6a572010-06-08 00:16:34 +00001570 llvm::APSInt Result(32);
1571 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1572 return ExprError(Diag(TheCall->getLocStart(),
1573 diag::err_shufflevector_nonconstant_argument)
1574 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001575
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001576 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001577 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001578 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001579 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001580 }
1581
Chris Lattner5f9e2722011-07-23 10:55:15 +00001582 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001583
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001584 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001585 exprs.push_back(TheCall->getArg(i));
1586 TheCall->setArg(i, 0);
1587 }
1588
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001589 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001590 TheCall->getCallee()->getLocStart(),
1591 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001592}
Chris Lattner30ce3442007-12-19 23:59:04 +00001593
Daniel Dunbar4493f792008-07-21 22:59:13 +00001594/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1595// This is declared to take (const void*, ...) and can take two
1596// optional constant int args.
1597bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001598 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001599
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001600 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001601 return Diag(TheCall->getLocEnd(),
1602 diag::err_typecheck_call_too_many_args_at_most)
1603 << 0 /*function call*/ << 3 << NumArgs
1604 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001605
1606 // Argument 0 is checked for us and the remaining arguments must be
1607 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001608 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001609 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001610
1611 // We can't check the value of a dependent argument.
1612 if (Arg->isTypeDependent() || Arg->isValueDependent())
1613 continue;
1614
Eli Friedman9aef7262009-12-04 00:30:06 +00001615 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001616 if (SemaBuiltinConstantArg(TheCall, i, Result))
1617 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Daniel Dunbar4493f792008-07-21 22:59:13 +00001619 // FIXME: gcc issues a warning and rewrites these to 0. These
1620 // seems especially odd for the third argument since the default
1621 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001622 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001623 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001624 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001625 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001626 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001627 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001628 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001629 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001630 }
1631 }
1632
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001633 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001634}
1635
Eric Christopher691ebc32010-04-17 02:26:23 +00001636/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1637/// TheCall is a constant expression.
1638bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1639 llvm::APSInt &Result) {
1640 Expr *Arg = TheCall->getArg(ArgNum);
1641 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1642 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1643
1644 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1645
1646 if (!Arg->isIntegerConstantExpr(Result, Context))
1647 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001648 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001649
Chris Lattner21fb98e2009-09-23 06:06:36 +00001650 return false;
1651}
1652
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001653/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1654/// int type). This simply type checks that type is one of the defined
1655/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001656// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001657bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001658 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001659
1660 // We can't check the value of a dependent argument.
1661 if (TheCall->getArg(1)->isTypeDependent() ||
1662 TheCall->getArg(1)->isValueDependent())
1663 return false;
1664
Eric Christopher691ebc32010-04-17 02:26:23 +00001665 // Check constant-ness first.
1666 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1667 return true;
1668
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001669 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001670 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001671 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1672 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001673 }
1674
1675 return false;
1676}
1677
Eli Friedman586d6a82009-05-03 06:04:26 +00001678/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001679/// This checks that val is a constant 1.
1680bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1681 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001682 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001683
Eric Christopher691ebc32010-04-17 02:26:23 +00001684 // TODO: This is less than ideal. Overload this to take a value.
1685 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1686 return true;
1687
1688 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001689 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1690 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1691
1692 return false;
1693}
1694
Richard Smith831421f2012-06-25 20:30:08 +00001695// Determine if an expression is a string literal or constant string.
1696// If this function returns false on the arguments to a function expecting a
1697// format string, we will usually need to emit a warning.
1698// True string literals are then checked by CheckFormatString.
1699Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001700Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1701 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001702 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001703 FormatStringType Type, VariadicCallType CallType,
1704 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001705 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001706 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001707 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001708
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001709 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001710
David Blaikiea73cdcb2012-02-10 21:07:25 +00001711 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1712 // Technically -Wformat-nonliteral does not warn about this case.
1713 // The behavior of printf and friends in this case is implementation
1714 // dependent. Ideally if the format string cannot be null then
1715 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001716 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001717
Ted Kremenekd30ef872009-01-12 23:09:09 +00001718 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001719 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001720 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001721 // The expression is a literal if both sub-expressions were, and it was
1722 // completely checked only if both sub-expressions were checked.
1723 const AbstractConditionalOperator *C =
1724 cast<AbstractConditionalOperator>(E);
1725 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001726 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001727 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001728 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001729 if (Left == SLCT_NotALiteral)
1730 return SLCT_NotALiteral;
1731 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001732 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001733 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001734 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001735 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001736 }
1737
1738 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001739 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1740 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001741 }
1742
John McCall56ca35d2011-02-17 10:25:35 +00001743 case Stmt::OpaqueValueExprClass:
1744 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1745 E = src;
1746 goto tryAgain;
1747 }
Richard Smith831421f2012-06-25 20:30:08 +00001748 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001749
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001750 case Stmt::PredefinedExprClass:
1751 // While __func__, etc., are technically not string literals, they
1752 // cannot contain format specifiers and thus are not a security
1753 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001754 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001755
Ted Kremenek082d9362009-03-20 21:35:28 +00001756 case Stmt::DeclRefExprClass: {
1757 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Ted Kremenek082d9362009-03-20 21:35:28 +00001759 // As an exception, do not flag errors for variables binding to
1760 // const string literals.
1761 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1762 bool isConstant = false;
1763 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001764
Ted Kremenek082d9362009-03-20 21:35:28 +00001765 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1766 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001767 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001768 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001769 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001770 } else if (T->isObjCObjectPointerType()) {
1771 // In ObjC, there is usually no "const ObjectPointer" type,
1772 // so don't check if the pointee type is constant.
1773 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001774 }
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Ted Kremenek082d9362009-03-20 21:35:28 +00001776 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001777 if (const Expr *Init = VD->getAnyInitializer()) {
1778 // Look through initializers like const char c[] = { "foo" }
1779 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1780 if (InitList->isStringLiteralInit())
1781 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1782 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001783 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001784 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001785 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001786 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001787 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anders Carlssond966a552009-06-28 19:55:58 +00001790 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1791 // special check to see if the format string is a function parameter
1792 // of the function calling the printf function. If the function
1793 // has an attribute indicating it is a printf-like function, then we
1794 // should suppress warnings concerning non-literals being used in a call
1795 // to a vprintf function. For example:
1796 //
1797 // void
1798 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1799 // va_list ap;
1800 // va_start(ap, fmt);
1801 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1802 // ...
1803 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001804 if (HasVAListArg) {
1805 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1806 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1807 int PVIndex = PV->getFunctionScopeIndex() + 1;
1808 for (specific_attr_iterator<FormatAttr>
1809 i = ND->specific_attr_begin<FormatAttr>(),
1810 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1811 FormatAttr *PVFormat = *i;
1812 // adjust for implicit parameter
1813 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1814 if (MD->isInstance())
1815 ++PVIndex;
1816 // We also check if the formats are compatible.
1817 // We can't pass a 'scanf' string to a 'printf' function.
1818 if (PVIndex == PVFormat->getFormatIdx() &&
1819 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001820 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001821 }
1822 }
1823 }
1824 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Richard Smith831421f2012-06-25 20:30:08 +00001827 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001828 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001829
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001830 case Stmt::CallExprClass:
1831 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001832 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001833 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1834 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1835 unsigned ArgIndex = FA->getFormatIdx();
1836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1837 if (MD->isInstance())
1838 --ArgIndex;
1839 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001841 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001842 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001843 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001844 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1845 unsigned BuiltinID = FD->getBuiltinID();
1846 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1847 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1848 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001849 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001850 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001851 firstDataArg, Type, CallType,
1852 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001853 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001854 }
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Richard Smith831421f2012-06-25 20:30:08 +00001857 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001858 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001859 case Stmt::ObjCStringLiteralClass:
1860 case Stmt::StringLiteralClass: {
1861 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Ted Kremenek082d9362009-03-20 21:35:28 +00001863 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001864 StrE = ObjCFExpr->getString();
1865 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001866 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Ted Kremenekd30ef872009-01-12 23:09:09 +00001868 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001869 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001870 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001871 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Richard Smith831421f2012-06-25 20:30:08 +00001874 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Ted Kremenek082d9362009-03-20 21:35:28 +00001877 default:
Richard Smith831421f2012-06-25 20:30:08 +00001878 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001879 }
1880}
1881
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001882void
Mike Stump1eb44332009-09-09 15:08:12 +00001883Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001884 const Expr * const *ExprArgs,
1885 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001886 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1887 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001888 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001889 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001890
1891 // As a special case, transparent unions initialized with zero are
1892 // considered null for the purposes of the nonnull attribute.
1893 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1894 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1895 if (const CompoundLiteralExpr *CLE =
1896 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1897 if (const InitListExpr *ILE =
1898 dyn_cast<InitListExpr>(CLE->getInitializer()))
1899 ArgExpr = ILE->getInit(0);
1900 }
1901
1902 bool Result;
1903 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001904 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001905 }
1906}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001907
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001908Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1909 return llvm::StringSwitch<FormatStringType>(Format->getType())
1910 .Case("scanf", FST_Scanf)
1911 .Cases("printf", "printf0", FST_Printf)
1912 .Cases("NSString", "CFString", FST_NSString)
1913 .Case("strftime", FST_Strftime)
1914 .Case("strfmon", FST_Strfmon)
1915 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1916 .Default(FST_Unknown);
1917}
1918
Jordan Roseddcfbc92012-07-19 18:10:23 +00001919/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001920/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001921/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001922bool Sema::CheckFormatArguments(const FormatAttr *Format,
1923 ArrayRef<const Expr *> Args,
1924 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001925 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001926 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001927 FormatStringInfo FSI;
1928 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001929 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001930 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001931 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001932 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001933}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001934
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001935bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001936 bool HasVAListArg, unsigned format_idx,
1937 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001938 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001939 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001940 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001941 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001942 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001943 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001946 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Chris Lattner59907c42007-08-10 20:18:51 +00001948 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001949 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001950 // Dynamically generated format strings are difficult to
1951 // automatically vet at compile time. Requiring that format strings
1952 // are string literals: (1) permits the checking of format strings by
1953 // the compiler and thereby (2) can practically remove the source of
1954 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001955
Mike Stump1eb44332009-09-09 15:08:12 +00001956 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001957 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001958 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001959 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001960 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001961 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001962 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001963 if (CT != SLCT_NotALiteral)
1964 // Literal format string found, check done!
1965 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001966
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001967 // Strftime is particular as it always uses a single 'time' argument,
1968 // so it is safe to pass a non-literal string.
1969 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001970 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001971
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001972 // Do not emit diag when the string param is a macro expansion and the
1973 // format is either NSString or CFString. This is a hack to prevent
1974 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1975 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001976 if (Type == FST_NSString &&
1977 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001978 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001979
Chris Lattner655f1412009-04-29 04:59:47 +00001980 // If there are no arguments specified, warn with -Wformat-security, otherwise
1981 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00001982 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001983 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001984 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001985 << OrigFormatExpr->getSourceRange();
1986 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001987 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001988 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001989 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001990 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001991}
Ted Kremenek71895b92007-08-14 17:39:48 +00001992
Ted Kremeneke0e53132010-01-28 23:39:18 +00001993namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001994class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1995protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001996 Sema &S;
1997 const StringLiteral *FExpr;
1998 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001999 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002000 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002001 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002002 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002003 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002004 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002005 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002006 bool usesPositionalArgs;
2007 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002008 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002009 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002010public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002011 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002012 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002013 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002014 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002015 unsigned formatIdx, bool inFunctionCall,
2016 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002017 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002018 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2019 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002020 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002021 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002022 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002023 CoveredArgs.resize(numDataArgs);
2024 CoveredArgs.reset();
2025 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002026
Ted Kremenek07d161f2010-01-29 01:50:07 +00002027 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002028
Ted Kremenek826a3452010-07-16 02:11:22 +00002029 void HandleIncompleteSpecifier(const char *startSpecifier,
2030 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002031
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002032 void HandleInvalidLengthModifier(
2033 const analyze_format_string::FormatSpecifier &FS,
2034 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002035 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002036
Hans Wennborg76517422012-02-22 10:17:01 +00002037 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002038 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002039 const char *startSpecifier, unsigned specifierLen);
2040
2041 void HandleNonStandardConversionSpecifier(
2042 const analyze_format_string::ConversionSpecifier &CS,
2043 const char *startSpecifier, unsigned specifierLen);
2044
Hans Wennborgf8562642012-03-09 10:10:54 +00002045 virtual void HandlePosition(const char *startPos, unsigned posLen);
2046
Ted Kremenekefaff192010-02-27 01:41:03 +00002047 virtual void HandleInvalidPosition(const char *startSpecifier,
2048 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002049 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002050
2051 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2052
Ted Kremeneke0e53132010-01-28 23:39:18 +00002053 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002054
Richard Trieu55733de2011-10-28 00:41:25 +00002055 template <typename Range>
2056 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2057 const Expr *ArgumentExpr,
2058 PartialDiagnostic PDiag,
2059 SourceLocation StringLoc,
2060 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002061 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002062
Ted Kremenek826a3452010-07-16 02:11:22 +00002063protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002064 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2065 const char *startSpec,
2066 unsigned specifierLen,
2067 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002068
2069 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2070 const char *startSpec,
2071 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002072
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002073 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002074 CharSourceRange getSpecifierRange(const char *startSpecifier,
2075 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002076 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002077
Ted Kremenek0d277352010-01-29 01:06:55 +00002078 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002079
2080 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2081 const analyze_format_string::ConversionSpecifier &CS,
2082 const char *startSpecifier, unsigned specifierLen,
2083 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002084
2085 template <typename Range>
2086 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2087 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002088 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002089
2090 void CheckPositionalAndNonpositionalArgs(
2091 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002092};
2093}
2094
Ted Kremenek826a3452010-07-16 02:11:22 +00002095SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002096 return OrigFormatExpr->getSourceRange();
2097}
2098
Ted Kremenek826a3452010-07-16 02:11:22 +00002099CharSourceRange CheckFormatHandler::
2100getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002101 SourceLocation Start = getLocationOfByte(startSpecifier);
2102 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2103
2104 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002105 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002106
2107 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002108}
2109
Ted Kremenek826a3452010-07-16 02:11:22 +00002110SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002111 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002112}
2113
Ted Kremenek826a3452010-07-16 02:11:22 +00002114void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2115 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002116 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2117 getLocationOfByte(startSpecifier),
2118 /*IsStringLocation*/true,
2119 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002120}
2121
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002122void CheckFormatHandler::HandleInvalidLengthModifier(
2123 const analyze_format_string::FormatSpecifier &FS,
2124 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002125 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002126 using namespace analyze_format_string;
2127
2128 const LengthModifier &LM = FS.getLengthModifier();
2129 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2130
2131 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002132 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002133 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002134 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002135 getLocationOfByte(LM.getStart()),
2136 /*IsStringLocation*/true,
2137 getSpecifierRange(startSpecifier, specifierLen));
2138
2139 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2140 << FixedLM->toString()
2141 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2142
2143 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002144 FixItHint Hint;
2145 if (DiagID == diag::warn_format_nonsensical_length)
2146 Hint = FixItHint::CreateRemoval(LMRange);
2147
2148 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002149 getLocationOfByte(LM.getStart()),
2150 /*IsStringLocation*/true,
2151 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002152 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002153 }
2154}
2155
Hans Wennborg76517422012-02-22 10:17:01 +00002156void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002157 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002158 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002159 using namespace analyze_format_string;
2160
2161 const LengthModifier &LM = FS.getLengthModifier();
2162 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2163
2164 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002165 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002166 if (FixedLM) {
2167 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2168 << LM.toString() << 0,
2169 getLocationOfByte(LM.getStart()),
2170 /*IsStringLocation*/true,
2171 getSpecifierRange(startSpecifier, specifierLen));
2172
2173 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2174 << FixedLM->toString()
2175 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2176
2177 } else {
2178 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2179 << LM.toString() << 0,
2180 getLocationOfByte(LM.getStart()),
2181 /*IsStringLocation*/true,
2182 getSpecifierRange(startSpecifier, specifierLen));
2183 }
Hans Wennborg76517422012-02-22 10:17:01 +00002184}
2185
2186void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2187 const analyze_format_string::ConversionSpecifier &CS,
2188 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002189 using namespace analyze_format_string;
2190
2191 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002192 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002193 if (FixedCS) {
2194 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2195 << CS.toString() << /*conversion specifier*/1,
2196 getLocationOfByte(CS.getStart()),
2197 /*IsStringLocation*/true,
2198 getSpecifierRange(startSpecifier, specifierLen));
2199
2200 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2201 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2202 << FixedCS->toString()
2203 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2204 } else {
2205 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2206 << CS.toString() << /*conversion specifier*/1,
2207 getLocationOfByte(CS.getStart()),
2208 /*IsStringLocation*/true,
2209 getSpecifierRange(startSpecifier, specifierLen));
2210 }
Hans Wennborg76517422012-02-22 10:17:01 +00002211}
2212
Hans Wennborgf8562642012-03-09 10:10:54 +00002213void CheckFormatHandler::HandlePosition(const char *startPos,
2214 unsigned posLen) {
2215 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2216 getLocationOfByte(startPos),
2217 /*IsStringLocation*/true,
2218 getSpecifierRange(startPos, posLen));
2219}
2220
Ted Kremenekefaff192010-02-27 01:41:03 +00002221void
Ted Kremenek826a3452010-07-16 02:11:22 +00002222CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2223 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002224 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2225 << (unsigned) p,
2226 getLocationOfByte(startPos), /*IsStringLocation*/true,
2227 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002228}
2229
Ted Kremenek826a3452010-07-16 02:11:22 +00002230void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002231 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2233 getLocationOfByte(startPos),
2234 /*IsStringLocation*/true,
2235 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002236}
2237
Ted Kremenek826a3452010-07-16 02:11:22 +00002238void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002239 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002240 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002241 EmitFormatDiagnostic(
2242 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2243 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2244 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002245 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002246}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002247
Jordan Rose48716662012-07-19 18:10:08 +00002248// Note that this may return NULL if there was an error parsing or building
2249// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002250const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002251 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002252}
2253
2254void CheckFormatHandler::DoneProcessing() {
2255 // Does the number of data arguments exceed the number of
2256 // format conversions in the format string?
2257 if (!HasVAListArg) {
2258 // Find any arguments that weren't covered.
2259 CoveredArgs.flip();
2260 signed notCoveredArg = CoveredArgs.find_first();
2261 if (notCoveredArg >= 0) {
2262 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002263 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2264 SourceLocation Loc = E->getLocStart();
2265 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2267 Loc, /*IsStringLocation*/false,
2268 getFormatStringRange());
2269 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002270 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002271 }
2272 }
2273}
2274
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002275bool
2276CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2277 SourceLocation Loc,
2278 const char *startSpec,
2279 unsigned specifierLen,
2280 const char *csStart,
2281 unsigned csLen) {
2282
2283 bool keepGoing = true;
2284 if (argIndex < NumDataArgs) {
2285 // Consider the argument coverered, even though the specifier doesn't
2286 // make sense.
2287 CoveredArgs.set(argIndex);
2288 }
2289 else {
2290 // If argIndex exceeds the number of data arguments we
2291 // don't issue a warning because that is just a cascade of warnings (and
2292 // they may have intended '%%' anyway). We don't want to continue processing
2293 // the format string after this point, however, as we will like just get
2294 // gibberish when trying to match arguments.
2295 keepGoing = false;
2296 }
2297
Richard Trieu55733de2011-10-28 00:41:25 +00002298 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2299 << StringRef(csStart, csLen),
2300 Loc, /*IsStringLocation*/true,
2301 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002302
2303 return keepGoing;
2304}
2305
Richard Trieu55733de2011-10-28 00:41:25 +00002306void
2307CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2308 const char *startSpec,
2309 unsigned specifierLen) {
2310 EmitFormatDiagnostic(
2311 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2312 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2313}
2314
Ted Kremenek666a1972010-07-26 19:45:42 +00002315bool
2316CheckFormatHandler::CheckNumArgs(
2317 const analyze_format_string::FormatSpecifier &FS,
2318 const analyze_format_string::ConversionSpecifier &CS,
2319 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2320
2321 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002322 PartialDiagnostic PDiag = FS.usesPositionalArg()
2323 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2324 << (argIndex+1) << NumDataArgs)
2325 : S.PDiag(diag::warn_printf_insufficient_data_args);
2326 EmitFormatDiagnostic(
2327 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2328 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002329 return false;
2330 }
2331 return true;
2332}
2333
Richard Trieu55733de2011-10-28 00:41:25 +00002334template<typename Range>
2335void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2336 SourceLocation Loc,
2337 bool IsStringLocation,
2338 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002339 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002340 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002341 Loc, IsStringLocation, StringRange, FixIt);
2342}
2343
2344/// \brief If the format string is not within the funcion call, emit a note
2345/// so that the function call and string are in diagnostic messages.
2346///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002347/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002348/// call and only one diagnostic message will be produced. Otherwise, an
2349/// extra note will be emitted pointing to location of the format string.
2350///
2351/// \param ArgumentExpr the expression that is passed as the format string
2352/// argument in the function call. Used for getting locations when two
2353/// diagnostics are emitted.
2354///
2355/// \param PDiag the callee should already have provided any strings for the
2356/// diagnostic message. This function only adds locations and fixits
2357/// to diagnostics.
2358///
2359/// \param Loc primary location for diagnostic. If two diagnostics are
2360/// required, one will be at Loc and a new SourceLocation will be created for
2361/// the other one.
2362///
2363/// \param IsStringLocation if true, Loc points to the format string should be
2364/// used for the note. Otherwise, Loc points to the argument list and will
2365/// be used with PDiag.
2366///
2367/// \param StringRange some or all of the string to highlight. This is
2368/// templated so it can accept either a CharSourceRange or a SourceRange.
2369///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002370/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002371template<typename Range>
2372void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2373 const Expr *ArgumentExpr,
2374 PartialDiagnostic PDiag,
2375 SourceLocation Loc,
2376 bool IsStringLocation,
2377 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002378 ArrayRef<FixItHint> FixIt) {
2379 if (InFunctionCall) {
2380 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2381 D << StringRange;
2382 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2383 I != E; ++I) {
2384 D << *I;
2385 }
2386 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002387 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2388 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002389
2390 const Sema::SemaDiagnosticBuilder &Note =
2391 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2392 diag::note_format_string_defined);
2393
2394 Note << StringRange;
2395 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2396 I != E; ++I) {
2397 Note << *I;
2398 }
Richard Trieu55733de2011-10-28 00:41:25 +00002399 }
2400}
2401
Ted Kremenek826a3452010-07-16 02:11:22 +00002402//===--- CHECK: Printf format string checking ------------------------------===//
2403
2404namespace {
2405class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002406 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002407public:
2408 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2409 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002410 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002411 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002412 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002413 unsigned formatIdx, bool inFunctionCall,
2414 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002415 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002416 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002417 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2418 {}
2419
Ted Kremenek826a3452010-07-16 02:11:22 +00002420
2421 bool HandleInvalidPrintfConversionSpecifier(
2422 const analyze_printf::PrintfSpecifier &FS,
2423 const char *startSpecifier,
2424 unsigned specifierLen);
2425
2426 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2427 const char *startSpecifier,
2428 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002429 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2430 const char *StartSpecifier,
2431 unsigned SpecifierLen,
2432 const Expr *E);
2433
Ted Kremenek826a3452010-07-16 02:11:22 +00002434 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2435 const char *startSpecifier, unsigned specifierLen);
2436 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2437 const analyze_printf::OptionalAmount &Amt,
2438 unsigned type,
2439 const char *startSpecifier, unsigned specifierLen);
2440 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2441 const analyze_printf::OptionalFlag &flag,
2442 const char *startSpecifier, unsigned specifierLen);
2443 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2444 const analyze_printf::OptionalFlag &ignoredFlag,
2445 const analyze_printf::OptionalFlag &flag,
2446 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002447 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002448 const Expr *E, const CharSourceRange &CSR);
2449
Ted Kremenek826a3452010-07-16 02:11:22 +00002450};
2451}
2452
2453bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2454 const analyze_printf::PrintfSpecifier &FS,
2455 const char *startSpecifier,
2456 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002457 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002458 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002459
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002460 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2461 getLocationOfByte(CS.getStart()),
2462 startSpecifier, specifierLen,
2463 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002464}
2465
Ted Kremenek826a3452010-07-16 02:11:22 +00002466bool CheckPrintfHandler::HandleAmount(
2467 const analyze_format_string::OptionalAmount &Amt,
2468 unsigned k, const char *startSpecifier,
2469 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002470
2471 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002472 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002473 unsigned argIndex = Amt.getArgIndex();
2474 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002475 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2476 << k,
2477 getLocationOfByte(Amt.getStart()),
2478 /*IsStringLocation*/true,
2479 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002480 // Don't do any more checking. We will just emit
2481 // spurious errors.
2482 return false;
2483 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002484
Ted Kremenek0d277352010-01-29 01:06:55 +00002485 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002486 // Although not in conformance with C99, we also allow the argument to be
2487 // an 'unsigned int' as that is a reasonably safe case. GCC also
2488 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002489 CoveredArgs.set(argIndex);
2490 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002491 if (!Arg)
2492 return false;
2493
Ted Kremenek0d277352010-01-29 01:06:55 +00002494 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002495
Hans Wennborgf3749f42012-08-07 08:11:26 +00002496 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2497 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002498
Hans Wennborgf3749f42012-08-07 08:11:26 +00002499 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002500 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002501 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002502 << T << Arg->getSourceRange(),
2503 getLocationOfByte(Amt.getStart()),
2504 /*IsStringLocation*/true,
2505 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002506 // Don't do any more checking. We will just emit
2507 // spurious errors.
2508 return false;
2509 }
2510 }
2511 }
2512 return true;
2513}
Ted Kremenek0d277352010-01-29 01:06:55 +00002514
Tom Caree4ee9662010-06-17 19:00:27 +00002515void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002516 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002517 const analyze_printf::OptionalAmount &Amt,
2518 unsigned type,
2519 const char *startSpecifier,
2520 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002521 const analyze_printf::PrintfConversionSpecifier &CS =
2522 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002523
Richard Trieu55733de2011-10-28 00:41:25 +00002524 FixItHint fixit =
2525 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2526 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2527 Amt.getConstantLength()))
2528 : FixItHint();
2529
2530 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2531 << type << CS.toString(),
2532 getLocationOfByte(Amt.getStart()),
2533 /*IsStringLocation*/true,
2534 getSpecifierRange(startSpecifier, specifierLen),
2535 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002536}
2537
Ted Kremenek826a3452010-07-16 02:11:22 +00002538void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002539 const analyze_printf::OptionalFlag &flag,
2540 const char *startSpecifier,
2541 unsigned specifierLen) {
2542 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002543 const analyze_printf::PrintfConversionSpecifier &CS =
2544 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002545 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2546 << flag.toString() << CS.toString(),
2547 getLocationOfByte(flag.getPosition()),
2548 /*IsStringLocation*/true,
2549 getSpecifierRange(startSpecifier, specifierLen),
2550 FixItHint::CreateRemoval(
2551 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002552}
2553
2554void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002555 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002556 const analyze_printf::OptionalFlag &ignoredFlag,
2557 const analyze_printf::OptionalFlag &flag,
2558 const char *startSpecifier,
2559 unsigned specifierLen) {
2560 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002561 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2562 << ignoredFlag.toString() << flag.toString(),
2563 getLocationOfByte(ignoredFlag.getPosition()),
2564 /*IsStringLocation*/true,
2565 getSpecifierRange(startSpecifier, specifierLen),
2566 FixItHint::CreateRemoval(
2567 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002568}
2569
Richard Smith831421f2012-06-25 20:30:08 +00002570// Determines if the specified is a C++ class or struct containing
2571// a member with the specified name and kind (e.g. a CXXMethodDecl named
2572// "c_str()").
2573template<typename MemberKind>
2574static llvm::SmallPtrSet<MemberKind*, 1>
2575CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2576 const RecordType *RT = Ty->getAs<RecordType>();
2577 llvm::SmallPtrSet<MemberKind*, 1> Results;
2578
2579 if (!RT)
2580 return Results;
2581 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2582 if (!RD)
2583 return Results;
2584
2585 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2586 Sema::LookupMemberName);
2587
2588 // We just need to include all members of the right kind turned up by the
2589 // filter, at this point.
2590 if (S.LookupQualifiedName(R, RT->getDecl()))
2591 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2592 NamedDecl *decl = (*I)->getUnderlyingDecl();
2593 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2594 Results.insert(FK);
2595 }
2596 return Results;
2597}
2598
2599// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002600// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002601// Returns true when a c_str() conversion method is found.
2602bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002603 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002604 const CharSourceRange &CSR) {
2605 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2606
2607 MethodSet Results =
2608 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2609
2610 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2611 MI != ME; ++MI) {
2612 const CXXMethodDecl *Method = *MI;
2613 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002614 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002615 // FIXME: Suggest parens if the expression needs them.
2616 SourceLocation EndLoc =
2617 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2618 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2619 << "c_str()"
2620 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2621 return true;
2622 }
2623 }
2624
2625 return false;
2626}
2627
Ted Kremeneke0e53132010-01-28 23:39:18 +00002628bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002629CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002630 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002631 const char *startSpecifier,
2632 unsigned specifierLen) {
2633
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002634 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002635 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002636 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002637
Ted Kremenekbaa40062010-07-19 22:01:06 +00002638 if (FS.consumesDataArgument()) {
2639 if (atFirstArg) {
2640 atFirstArg = false;
2641 usesPositionalArgs = FS.usesPositionalArg();
2642 }
2643 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002644 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2645 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002646 return false;
2647 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002648 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002649
Ted Kremenekefaff192010-02-27 01:41:03 +00002650 // First check if the field width, precision, and conversion specifier
2651 // have matching data arguments.
2652 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2653 startSpecifier, specifierLen)) {
2654 return false;
2655 }
2656
2657 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2658 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002659 return false;
2660 }
2661
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002662 if (!CS.consumesDataArgument()) {
2663 // FIXME: Technically specifying a precision or field width here
2664 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002665 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002666 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002667
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002668 // Consume the argument.
2669 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002670 if (argIndex < NumDataArgs) {
2671 // The check to see if the argIndex is valid will come later.
2672 // We set the bit here because we may exit early from this
2673 // function if we encounter some other error.
2674 CoveredArgs.set(argIndex);
2675 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002676
2677 // Check for using an Objective-C specific conversion specifier
2678 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002679 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002680 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2681 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002682 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002683
Tom Caree4ee9662010-06-17 19:00:27 +00002684 // Check for invalid use of field width
2685 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002686 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002687 startSpecifier, specifierLen);
2688 }
2689
2690 // Check for invalid use of precision
2691 if (!FS.hasValidPrecision()) {
2692 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2693 startSpecifier, specifierLen);
2694 }
2695
2696 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002697 if (!FS.hasValidThousandsGroupingPrefix())
2698 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002699 if (!FS.hasValidLeadingZeros())
2700 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2701 if (!FS.hasValidPlusPrefix())
2702 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002703 if (!FS.hasValidSpacePrefix())
2704 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002705 if (!FS.hasValidAlternativeForm())
2706 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2707 if (!FS.hasValidLeftJustified())
2708 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2709
2710 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002711 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2712 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2713 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002714 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2715 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2716 startSpecifier, specifierLen);
2717
2718 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002719 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002720 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2721 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002722 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002723 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002724 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002725 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2726 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002727
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002728 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2729 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2730
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002731 // The remaining checks depend on the data arguments.
2732 if (HasVAListArg)
2733 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002734
Ted Kremenek666a1972010-07-26 19:45:42 +00002735 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002736 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002737
Jordan Rose48716662012-07-19 18:10:08 +00002738 const Expr *Arg = getDataArg(argIndex);
2739 if (!Arg)
2740 return true;
2741
2742 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002743}
2744
Jordan Roseec087352012-09-05 22:56:26 +00002745static bool requiresParensToAddCast(const Expr *E) {
2746 // FIXME: We should have a general way to reason about operator
2747 // precedence and whether parens are actually needed here.
2748 // Take care of a few common cases where they aren't.
2749 const Expr *Inside = E->IgnoreImpCasts();
2750 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2751 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2752
2753 switch (Inside->getStmtClass()) {
2754 case Stmt::ArraySubscriptExprClass:
2755 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002756 case Stmt::CharacterLiteralClass:
2757 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002758 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002759 case Stmt::FloatingLiteralClass:
2760 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002761 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002762 case Stmt::ObjCArrayLiteralClass:
2763 case Stmt::ObjCBoolLiteralExprClass:
2764 case Stmt::ObjCBoxedExprClass:
2765 case Stmt::ObjCDictionaryLiteralClass:
2766 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002767 case Stmt::ObjCIvarRefExprClass:
2768 case Stmt::ObjCMessageExprClass:
2769 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002770 case Stmt::ObjCStringLiteralClass:
2771 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002772 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002773 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002774 case Stmt::UnaryOperatorClass:
2775 return false;
2776 default:
2777 return true;
2778 }
2779}
2780
Richard Smith831421f2012-06-25 20:30:08 +00002781bool
2782CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2783 const char *StartSpecifier,
2784 unsigned SpecifierLen,
2785 const Expr *E) {
2786 using namespace analyze_format_string;
2787 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002788 // Now type check the data expression that matches the
2789 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002790 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2791 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002792 if (!AT.isValid())
2793 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002794
Jordan Rose448ac3e2012-12-05 18:44:40 +00002795 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002796 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2797 ExprTy = TET->getUnderlyingExpr()->getType();
2798 }
2799
Jordan Rose448ac3e2012-12-05 18:44:40 +00002800 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002801 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002802
Jordan Rose614a8652012-09-05 22:56:19 +00002803 // Look through argument promotions for our error message's reported type.
2804 // This includes the integral and floating promotions, but excludes array
2805 // and function pointer decay; seeing that an argument intended to be a
2806 // string has type 'char [6]' is probably more confusing than 'char *'.
2807 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2808 if (ICE->getCastKind() == CK_IntegralCast ||
2809 ICE->getCastKind() == CK_FloatingCast) {
2810 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002811 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002812
2813 // Check if we didn't match because of an implicit cast from a 'char'
2814 // or 'short' to an 'int'. This is done because printf is a varargs
2815 // function.
2816 if (ICE->getType() == S.Context.IntTy ||
2817 ICE->getType() == S.Context.UnsignedIntTy) {
2818 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002819 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002820 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002821 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002822 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002823 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2824 // Special case for 'a', which has type 'int' in C.
2825 // Note, however, that we do /not/ want to treat multibyte constants like
2826 // 'MooV' as characters! This form is deprecated but still exists.
2827 if (ExprTy == S.Context.IntTy)
2828 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2829 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002830 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002831
Jordan Rose2cd34402012-12-05 18:44:49 +00002832 // %C in an Objective-C context prints a unichar, not a wchar_t.
2833 // If the argument is an integer of some kind, believe the %C and suggest
2834 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002835 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002836 if (ObjCContext &&
2837 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2838 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2839 !ExprTy->isCharType()) {
2840 // 'unichar' is defined as a typedef of unsigned short, but we should
2841 // prefer using the typedef if it is visible.
2842 IntendedTy = S.Context.UnsignedShortTy;
2843
2844 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2845 Sema::LookupOrdinaryName);
2846 if (S.LookupName(Result, S.getCurScope())) {
2847 NamedDecl *ND = Result.getFoundDecl();
2848 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2849 if (TD->getUnderlyingType() == IntendedTy)
2850 IntendedTy = S.Context.getTypedefType(TD);
2851 }
2852 }
2853 }
2854
2855 // Special-case some of Darwin's platform-independence types by suggesting
2856 // casts to primitive types that are known to be large enough.
2857 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002858 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002859 // Use a 'while' to peel off layers of typedefs.
2860 QualType TyTy = IntendedTy;
2861 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002862 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002863 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002864 .Case("NSInteger", S.Context.LongTy)
2865 .Case("NSUInteger", S.Context.UnsignedLongTy)
2866 .Case("SInt32", S.Context.IntTy)
2867 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002868 .Default(QualType());
2869
2870 if (!CastTy.isNull()) {
2871 ShouldNotPrintDirectly = true;
2872 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002873 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002874 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002875 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002876 }
2877 }
2878
Jordan Rose614a8652012-09-05 22:56:19 +00002879 // We may be able to offer a FixItHint if it is a supported type.
2880 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002881 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002882 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002883
Jordan Rose614a8652012-09-05 22:56:19 +00002884 if (success) {
2885 // Get the fix string from the fixed format specifier
2886 SmallString<16> buf;
2887 llvm::raw_svector_ostream os(buf);
2888 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002889
Jordan Roseec087352012-09-05 22:56:26 +00002890 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2891
Jordan Rose2cd34402012-12-05 18:44:49 +00002892 if (IntendedTy == ExprTy) {
2893 // In this case, the specifier is wrong and should be changed to match
2894 // the argument.
2895 EmitFormatDiagnostic(
2896 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2897 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2898 << E->getSourceRange(),
2899 E->getLocStart(),
2900 /*IsStringLocation*/false,
2901 SpecRange,
2902 FixItHint::CreateReplacement(SpecRange, os.str()));
2903
2904 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002905 // The canonical type for formatting this value is different from the
2906 // actual type of the expression. (This occurs, for example, with Darwin's
2907 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2908 // should be printed as 'long' for 64-bit compatibility.)
2909 // Rather than emitting a normal format/argument mismatch, we want to
2910 // add a cast to the recommended type (and correct the format string
2911 // if necessary).
2912 SmallString<16> CastBuf;
2913 llvm::raw_svector_ostream CastFix(CastBuf);
2914 CastFix << "(";
2915 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2916 CastFix << ")";
2917
2918 SmallVector<FixItHint,4> Hints;
2919 if (!AT.matchesType(S.Context, IntendedTy))
2920 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2921
2922 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2923 // If there's already a cast present, just replace it.
2924 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2925 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2926
2927 } else if (!requiresParensToAddCast(E)) {
2928 // If the expression has high enough precedence,
2929 // just write the C-style cast.
2930 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2931 CastFix.str()));
2932 } else {
2933 // Otherwise, add parens around the expression as well as the cast.
2934 CastFix << "(";
2935 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2936 CastFix.str()));
2937
2938 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2939 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2940 }
2941
Jordan Rose2cd34402012-12-05 18:44:49 +00002942 if (ShouldNotPrintDirectly) {
2943 // The expression has a type that should not be printed directly.
2944 // We extract the name from the typedef because we don't want to show
2945 // the underlying type in the diagnostic.
2946 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002947
Jordan Rose2cd34402012-12-05 18:44:49 +00002948 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2949 << Name << IntendedTy
2950 << E->getSourceRange(),
2951 E->getLocStart(), /*IsStringLocation=*/false,
2952 SpecRange, Hints);
2953 } else {
2954 // In this case, the expression could be printed using a different
2955 // specifier, but we've decided that the specifier is probably correct
2956 // and we should cast instead. Just use the normal warning message.
2957 EmitFormatDiagnostic(
2958 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2959 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2960 << E->getSourceRange(),
2961 E->getLocStart(), /*IsStringLocation*/false,
2962 SpecRange, Hints);
2963 }
Jordan Roseec087352012-09-05 22:56:26 +00002964 }
Jordan Rose614a8652012-09-05 22:56:19 +00002965 } else {
2966 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2967 SpecifierLen);
2968 // Since the warning for passing non-POD types to variadic functions
2969 // was deferred until now, we emit a warning for non-POD
2970 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002971 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002972 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002973 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002974 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2975 else
2976 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2977
2978 EmitFormatDiagnostic(
2979 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002980 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002981 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002982 << CallType
2983 << AT.getRepresentativeTypeName(S.Context)
2984 << CSR
2985 << E->getSourceRange(),
2986 E->getLocStart(), /*IsStringLocation*/false, CSR);
2987
2988 checkForCStrMembers(AT, E, CSR);
2989 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002990 EmitFormatDiagnostic(
2991 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002992 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002993 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002994 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002995 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002996 }
2997
Ted Kremeneke0e53132010-01-28 23:39:18 +00002998 return true;
2999}
3000
Ted Kremenek826a3452010-07-16 02:11:22 +00003001//===--- CHECK: Scanf format string checking ------------------------------===//
3002
3003namespace {
3004class CheckScanfHandler : public CheckFormatHandler {
3005public:
3006 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3007 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003008 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003009 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003010 unsigned formatIdx, bool inFunctionCall,
3011 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00003012 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003013 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003014 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003015 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003016
3017 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3018 const char *startSpecifier,
3019 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003020
3021 bool HandleInvalidScanfConversionSpecifier(
3022 const analyze_scanf::ScanfSpecifier &FS,
3023 const char *startSpecifier,
3024 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003025
3026 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003027};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003028}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003029
Ted Kremenekb7c21012010-07-16 18:28:03 +00003030void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3031 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003032 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3033 getLocationOfByte(end), /*IsStringLocation*/true,
3034 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003035}
3036
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003037bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3038 const analyze_scanf::ScanfSpecifier &FS,
3039 const char *startSpecifier,
3040 unsigned specifierLen) {
3041
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003042 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003043 FS.getConversionSpecifier();
3044
3045 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3046 getLocationOfByte(CS.getStart()),
3047 startSpecifier, specifierLen,
3048 CS.getStart(), CS.getLength());
3049}
3050
Ted Kremenek826a3452010-07-16 02:11:22 +00003051bool CheckScanfHandler::HandleScanfSpecifier(
3052 const analyze_scanf::ScanfSpecifier &FS,
3053 const char *startSpecifier,
3054 unsigned specifierLen) {
3055
3056 using namespace analyze_scanf;
3057 using namespace analyze_format_string;
3058
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003059 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003060
Ted Kremenekbaa40062010-07-19 22:01:06 +00003061 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3062 // be used to decide if we are using positional arguments consistently.
3063 if (FS.consumesDataArgument()) {
3064 if (atFirstArg) {
3065 atFirstArg = false;
3066 usesPositionalArgs = FS.usesPositionalArg();
3067 }
3068 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003069 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3070 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003071 return false;
3072 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003073 }
3074
3075 // Check if the field with is non-zero.
3076 const OptionalAmount &Amt = FS.getFieldWidth();
3077 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3078 if (Amt.getConstantAmount() == 0) {
3079 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3080 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003081 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3082 getLocationOfByte(Amt.getStart()),
3083 /*IsStringLocation*/true, R,
3084 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003085 }
3086 }
3087
3088 if (!FS.consumesDataArgument()) {
3089 // FIXME: Technically specifying a precision or field width here
3090 // makes no sense. Worth issuing a warning at some point.
3091 return true;
3092 }
3093
3094 // Consume the argument.
3095 unsigned argIndex = FS.getArgIndex();
3096 if (argIndex < NumDataArgs) {
3097 // The check to see if the argIndex is valid will come later.
3098 // We set the bit here because we may exit early from this
3099 // function if we encounter some other error.
3100 CoveredArgs.set(argIndex);
3101 }
3102
Ted Kremenek1e51c202010-07-20 20:04:47 +00003103 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003104 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003105 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3106 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003107 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003108 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003109 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3111 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003112
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003113 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3114 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3115
Ted Kremenek826a3452010-07-16 02:11:22 +00003116 // The remaining checks depend on the data arguments.
3117 if (HasVAListArg)
3118 return true;
3119
Ted Kremenek666a1972010-07-26 19:45:42 +00003120 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003121 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003122
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003123 // Check that the argument type matches the format specifier.
3124 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003125 if (!Ex)
3126 return true;
3127
Hans Wennborg58e1e542012-08-07 08:59:46 +00003128 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3129 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003130 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003131 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003132 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003133
3134 if (success) {
3135 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003136 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003137 llvm::raw_svector_ostream os(buf);
3138 fixedFS.toString(os);
3139
3140 EmitFormatDiagnostic(
3141 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003142 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003143 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003144 Ex->getLocStart(),
3145 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003146 getSpecifierRange(startSpecifier, specifierLen),
3147 FixItHint::CreateReplacement(
3148 getSpecifierRange(startSpecifier, specifierLen),
3149 os.str()));
3150 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003151 EmitFormatDiagnostic(
3152 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003153 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003154 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003155 Ex->getLocStart(),
3156 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003157 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003158 }
3159 }
3160
Ted Kremenek826a3452010-07-16 02:11:22 +00003161 return true;
3162}
3163
3164void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003165 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003166 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003167 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003168 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003169 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003170
Ted Kremeneke0e53132010-01-28 23:39:18 +00003171 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003172 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003173 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003174 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003175 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3176 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003177 return;
3178 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003179
Ted Kremeneke0e53132010-01-28 23:39:18 +00003180 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003181 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003182 const char *Str = StrRef.data();
3183 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003184 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003185
Ted Kremeneke0e53132010-01-28 23:39:18 +00003186 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003187 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003188 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003189 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003190 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3191 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003192 return;
3193 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003194
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003195 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003196 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003197 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003198 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003199 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003200
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003201 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003202 getLangOpts(),
3203 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003204 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003205 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003206 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003207 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003208 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003209
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003210 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003211 getLangOpts(),
3212 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003213 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003214 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003215}
3216
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003217//===--- CHECK: Standard memory functions ---------------------------------===//
3218
Douglas Gregor2a053a32011-05-03 20:05:22 +00003219/// \brief Determine whether the given type is a dynamic class type (e.g.,
3220/// whether it has a vtable).
3221static bool isDynamicClassType(QualType T) {
3222 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3223 if (CXXRecordDecl *Definition = Record->getDefinition())
3224 if (Definition->isDynamicClass())
3225 return true;
3226
3227 return false;
3228}
3229
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003230/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003231/// otherwise returns NULL.
3232static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003233 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003234 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3235 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3236 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003237
Chandler Carruth000d4282011-06-16 09:09:40 +00003238 return 0;
3239}
3240
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003241/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003242static QualType getSizeOfArgType(const Expr* E) {
3243 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3244 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3245 if (SizeOf->getKind() == clang::UETT_SizeOf)
3246 return SizeOf->getTypeOfArgument();
3247
3248 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003249}
3250
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003251/// \brief Check for dangerous or invalid arguments to memset().
3252///
Chandler Carruth929f0132011-06-03 06:23:57 +00003253/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003254/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3255/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003256///
3257/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003258void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003259 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003260 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003261 assert(BId != 0);
3262
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003263 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003264 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003265 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003266 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003267 return;
3268
Anna Zaks0a151a12012-01-17 00:37:07 +00003269 unsigned LastArg = (BId == Builtin::BImemset ||
3270 BId == Builtin::BIstrndup ? 1 : 2);
3271 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003272 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003273
3274 // We have special checking when the length is a sizeof expression.
3275 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3276 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3277 llvm::FoldingSetNodeID SizeOfArgID;
3278
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003279 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3280 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003281 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003282
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003283 QualType DestTy = Dest->getType();
3284 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3285 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003286
Chandler Carruth000d4282011-06-16 09:09:40 +00003287 // Never warn about void type pointers. This can be used to suppress
3288 // false positives.
3289 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003290 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003291
Chandler Carruth000d4282011-06-16 09:09:40 +00003292 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3293 // actually comparing the expressions for equality. Because computing the
3294 // expression IDs can be expensive, we only do this if the diagnostic is
3295 // enabled.
3296 if (SizeOfArg &&
3297 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3298 SizeOfArg->getExprLoc())) {
3299 // We only compute IDs for expressions if the warning is enabled, and
3300 // cache the sizeof arg's ID.
3301 if (SizeOfArgID == llvm::FoldingSetNodeID())
3302 SizeOfArg->Profile(SizeOfArgID, Context, true);
3303 llvm::FoldingSetNodeID DestID;
3304 Dest->Profile(DestID, Context, true);
3305 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003306 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3307 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003308 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003309 StringRef ReadableName = FnName->getName();
3310
Chandler Carruth000d4282011-06-16 09:09:40 +00003311 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003312 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003313 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003314 if (!PointeeTy->isIncompleteType() &&
3315 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003316 ActionIdx = 2; // If the pointee's size is sizeof(char),
3317 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003318
3319 // If the function is defined as a builtin macro, do not show macro
3320 // expansion.
3321 SourceLocation SL = SizeOfArg->getExprLoc();
3322 SourceRange DSR = Dest->getSourceRange();
3323 SourceRange SSR = SizeOfArg->getSourceRange();
3324 SourceManager &SM = PP.getSourceManager();
3325
3326 if (SM.isMacroArgExpansion(SL)) {
3327 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3328 SL = SM.getSpellingLoc(SL);
3329 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3330 SM.getSpellingLoc(DSR.getEnd()));
3331 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3332 SM.getSpellingLoc(SSR.getEnd()));
3333 }
3334
Anna Zaks90c78322012-05-30 23:14:52 +00003335 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003336 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003337 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003338 << PointeeTy
3339 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003340 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003341 << SSR);
3342 DiagRuntimeBehavior(SL, SizeOfArg,
3343 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3344 << ActionIdx
3345 << SSR);
3346
Chandler Carruth000d4282011-06-16 09:09:40 +00003347 break;
3348 }
3349 }
3350
3351 // Also check for cases where the sizeof argument is the exact same
3352 // type as the memory argument, and where it points to a user-defined
3353 // record type.
3354 if (SizeOfArgTy != QualType()) {
3355 if (PointeeTy->isRecordType() &&
3356 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3357 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3358 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3359 << FnName << SizeOfArgTy << ArgIdx
3360 << PointeeTy << Dest->getSourceRange()
3361 << LenExpr->getSourceRange());
3362 break;
3363 }
Nico Webere4a1c642011-06-14 16:14:58 +00003364 }
3365
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003366 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003367 if (isDynamicClassType(PointeeTy)) {
3368
3369 unsigned OperationType = 0;
3370 // "overwritten" if we're warning about the destination for any call
3371 // but memcmp; otherwise a verb appropriate to the call.
3372 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3373 if (BId == Builtin::BImemcpy)
3374 OperationType = 1;
3375 else if(BId == Builtin::BImemmove)
3376 OperationType = 2;
3377 else if (BId == Builtin::BImemcmp)
3378 OperationType = 3;
3379 }
3380
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003381 DiagRuntimeBehavior(
3382 Dest->getExprLoc(), Dest,
3383 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003384 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003385 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003386 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003387 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003388 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3389 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003390 DiagRuntimeBehavior(
3391 Dest->getExprLoc(), Dest,
3392 PDiag(diag::warn_arc_object_memaccess)
3393 << ArgIdx << FnName << PointeeTy
3394 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003395 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003396 continue;
John McCallf85e1932011-06-15 23:02:42 +00003397
3398 DiagRuntimeBehavior(
3399 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003400 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003401 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3402 break;
3403 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003404 }
3405}
3406
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003407// A little helper routine: ignore addition and subtraction of integer literals.
3408// This intentionally does not ignore all integer constant expressions because
3409// we don't want to remove sizeof().
3410static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3411 Ex = Ex->IgnoreParenCasts();
3412
3413 for (;;) {
3414 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3415 if (!BO || !BO->isAdditiveOp())
3416 break;
3417
3418 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3419 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3420
3421 if (isa<IntegerLiteral>(RHS))
3422 Ex = LHS;
3423 else if (isa<IntegerLiteral>(LHS))
3424 Ex = RHS;
3425 else
3426 break;
3427 }
3428
3429 return Ex;
3430}
3431
Anna Zaks0f38ace2012-08-08 21:42:23 +00003432static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3433 ASTContext &Context) {
3434 // Only handle constant-sized or VLAs, but not flexible members.
3435 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3436 // Only issue the FIXIT for arrays of size > 1.
3437 if (CAT->getSize().getSExtValue() <= 1)
3438 return false;
3439 } else if (!Ty->isVariableArrayType()) {
3440 return false;
3441 }
3442 return true;
3443}
3444
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003445// Warn if the user has made the 'size' argument to strlcpy or strlcat
3446// be the size of the source, instead of the destination.
3447void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3448 IdentifierInfo *FnName) {
3449
3450 // Don't crash if the user has the wrong number of arguments
3451 if (Call->getNumArgs() != 3)
3452 return;
3453
3454 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3455 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3456 const Expr *CompareWithSrc = NULL;
3457
3458 // Look for 'strlcpy(dst, x, sizeof(x))'
3459 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3460 CompareWithSrc = Ex;
3461 else {
3462 // Look for 'strlcpy(dst, x, strlen(x))'
3463 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003464 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003465 && SizeCall->getNumArgs() == 1)
3466 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3467 }
3468 }
3469
3470 if (!CompareWithSrc)
3471 return;
3472
3473 // Determine if the argument to sizeof/strlen is equal to the source
3474 // argument. In principle there's all kinds of things you could do
3475 // here, for instance creating an == expression and evaluating it with
3476 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3477 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3478 if (!SrcArgDRE)
3479 return;
3480
3481 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3482 if (!CompareWithSrcDRE ||
3483 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3484 return;
3485
3486 const Expr *OriginalSizeArg = Call->getArg(2);
3487 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3488 << OriginalSizeArg->getSourceRange() << FnName;
3489
3490 // Output a FIXIT hint if the destination is an array (rather than a
3491 // pointer to an array). This could be enhanced to handle some
3492 // pointers if we know the actual size, like if DstArg is 'array+2'
3493 // we could say 'sizeof(array)-2'.
3494 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003495 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003496 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003497
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003498 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003499 llvm::raw_svector_ostream OS(sizeString);
3500 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003501 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003502 OS << ")";
3503
3504 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3505 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3506 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003507}
3508
Anna Zaksc36bedc2012-02-01 19:08:57 +00003509/// Check if two expressions refer to the same declaration.
3510static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3511 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3512 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3513 return D1->getDecl() == D2->getDecl();
3514 return false;
3515}
3516
3517static const Expr *getStrlenExprArg(const Expr *E) {
3518 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3519 const FunctionDecl *FD = CE->getDirectCallee();
3520 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3521 return 0;
3522 return CE->getArg(0)->IgnoreParenCasts();
3523 }
3524 return 0;
3525}
3526
3527// Warn on anti-patterns as the 'size' argument to strncat.
3528// The correct size argument should look like following:
3529// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3530void Sema::CheckStrncatArguments(const CallExpr *CE,
3531 IdentifierInfo *FnName) {
3532 // Don't crash if the user has the wrong number of arguments.
3533 if (CE->getNumArgs() < 3)
3534 return;
3535 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3536 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3537 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3538
3539 // Identify common expressions, which are wrongly used as the size argument
3540 // to strncat and may lead to buffer overflows.
3541 unsigned PatternType = 0;
3542 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3543 // - sizeof(dst)
3544 if (referToTheSameDecl(SizeOfArg, DstArg))
3545 PatternType = 1;
3546 // - sizeof(src)
3547 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3548 PatternType = 2;
3549 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3550 if (BE->getOpcode() == BO_Sub) {
3551 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3552 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3553 // - sizeof(dst) - strlen(dst)
3554 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3555 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3556 PatternType = 1;
3557 // - sizeof(src) - (anything)
3558 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3559 PatternType = 2;
3560 }
3561 }
3562
3563 if (PatternType == 0)
3564 return;
3565
Anna Zaksafdb0412012-02-03 01:27:37 +00003566 // Generate the diagnostic.
3567 SourceLocation SL = LenArg->getLocStart();
3568 SourceRange SR = LenArg->getSourceRange();
3569 SourceManager &SM = PP.getSourceManager();
3570
3571 // If the function is defined as a builtin macro, do not show macro expansion.
3572 if (SM.isMacroArgExpansion(SL)) {
3573 SL = SM.getSpellingLoc(SL);
3574 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3575 SM.getSpellingLoc(SR.getEnd()));
3576 }
3577
Anna Zaks0f38ace2012-08-08 21:42:23 +00003578 // Check if the destination is an array (rather than a pointer to an array).
3579 QualType DstTy = DstArg->getType();
3580 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3581 Context);
3582 if (!isKnownSizeArray) {
3583 if (PatternType == 1)
3584 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3585 else
3586 Diag(SL, diag::warn_strncat_src_size) << SR;
3587 return;
3588 }
3589
Anna Zaksc36bedc2012-02-01 19:08:57 +00003590 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003591 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003592 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003593 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003594
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003595 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003596 llvm::raw_svector_ostream OS(sizeString);
3597 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003598 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003599 OS << ") - ";
3600 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003601 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003602 OS << ") - 1";
3603
Anna Zaksafdb0412012-02-03 01:27:37 +00003604 Diag(SL, diag::note_strncat_wrong_size)
3605 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003606}
3607
Ted Kremenek06de2762007-08-17 16:46:58 +00003608//===--- CHECK: Return Address of Stack Variable --------------------------===//
3609
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003610static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3611 Decl *ParentDecl);
3612static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3613 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003614
3615/// CheckReturnStackAddr - Check if a return statement returns the address
3616/// of a stack variable.
3617void
3618Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3619 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003621 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003622 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003623
3624 // Perform checking for returned stack addresses, local blocks,
3625 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003626 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003627 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003628 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003629 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003630 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003631 }
3632
3633 if (stackE == 0)
3634 return; // Nothing suspicious was found.
3635
3636 SourceLocation diagLoc;
3637 SourceRange diagRange;
3638 if (refVars.empty()) {
3639 diagLoc = stackE->getLocStart();
3640 diagRange = stackE->getSourceRange();
3641 } else {
3642 // We followed through a reference variable. 'stackE' contains the
3643 // problematic expression but we will warn at the return statement pointing
3644 // at the reference variable. We will later display the "trail" of
3645 // reference variables using notes.
3646 diagLoc = refVars[0]->getLocStart();
3647 diagRange = refVars[0]->getSourceRange();
3648 }
3649
3650 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3651 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3652 : diag::warn_ret_stack_addr)
3653 << DR->getDecl()->getDeclName() << diagRange;
3654 } else if (isa<BlockExpr>(stackE)) { // local block.
3655 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3656 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3657 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3658 } else { // local temporary.
3659 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3660 : diag::warn_ret_local_temp_addr)
3661 << diagRange;
3662 }
3663
3664 // Display the "trail" of reference variables that we followed until we
3665 // found the problematic expression using notes.
3666 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3667 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3668 // If this var binds to another reference var, show the range of the next
3669 // var, otherwise the var binds to the problematic expression, in which case
3670 // show the range of the expression.
3671 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3672 : stackE->getSourceRange();
3673 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3674 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003675 }
3676}
3677
3678/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3679/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003680/// to a location on the stack, a local block, an address of a label, or a
3681/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003682/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003683/// encounter a subexpression that (1) clearly does not lead to one of the
3684/// above problematic expressions (2) is something we cannot determine leads to
3685/// a problematic expression based on such local checking.
3686///
3687/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3688/// the expression that they point to. Such variables are added to the
3689/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003690///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003691/// EvalAddr processes expressions that are pointers that are used as
3692/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003693/// At the base case of the recursion is a check for the above problematic
3694/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003695///
3696/// This implementation handles:
3697///
3698/// * pointer-to-pointer casts
3699/// * implicit conversions from array references to pointers
3700/// * taking the address of fields
3701/// * arbitrary interplay between "&" and "*" operators
3702/// * pointer arithmetic from an address of a stack variable
3703/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003704static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3705 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003706 if (E->isTypeDependent())
3707 return NULL;
3708
Ted Kremenek06de2762007-08-17 16:46:58 +00003709 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003710 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003711 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003712 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003713 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Peter Collingbournef111d932011-04-15 00:35:48 +00003715 E = E->IgnoreParens();
3716
Ted Kremenek06de2762007-08-17 16:46:58 +00003717 // Our "symbolic interpreter" is just a dispatch off the currently
3718 // viewed AST node. We then recursively traverse the AST by calling
3719 // EvalAddr and EvalVal appropriately.
3720 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003721 case Stmt::DeclRefExprClass: {
3722 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3723
3724 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3725 // If this is a reference variable, follow through to the expression that
3726 // it points to.
3727 if (V->hasLocalStorage() &&
3728 V->getType()->isReferenceType() && V->hasInit()) {
3729 // Add the reference variable to the "trail".
3730 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003731 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003732 }
3733
3734 return NULL;
3735 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003736
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003737 case Stmt::UnaryOperatorClass: {
3738 // The only unary operator that make sense to handle here
3739 // is AddrOf. All others don't make sense as pointers.
3740 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003741
John McCall2de56d12010-08-25 11:45:40 +00003742 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003743 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003744 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003745 return NULL;
3746 }
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003748 case Stmt::BinaryOperatorClass: {
3749 // Handle pointer arithmetic. All other binary operators are not valid
3750 // in this context.
3751 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003752 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003753
John McCall2de56d12010-08-25 11:45:40 +00003754 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003755 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003757 Expr *Base = B->getLHS();
3758
3759 // Determine which argument is the real pointer base. It could be
3760 // the RHS argument instead of the LHS.
3761 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003763 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003764 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003765 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003766
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003767 // For conditional operators we need to see if either the LHS or RHS are
3768 // valid DeclRefExpr*s. If one of them is valid, we return it.
3769 case Stmt::ConditionalOperatorClass: {
3770 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003772 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003773 if (Expr *lhsExpr = C->getLHS()) {
3774 // In C++, we can have a throw-expression, which has 'void' type.
3775 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003776 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003777 return LHS;
3778 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003779
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003780 // In C++, we can have a throw-expression, which has 'void' type.
3781 if (C->getRHS()->getType()->isVoidType())
3782 return NULL;
3783
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003784 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003785 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003786
3787 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003788 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003789 return E; // local block.
3790 return NULL;
3791
3792 case Stmt::AddrLabelExprClass:
3793 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003794
John McCall80ee6e82011-11-10 05:35:25 +00003795 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003796 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3797 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003798
Ted Kremenek54b52742008-08-07 00:49:01 +00003799 // For casts, we need to handle conversions from arrays to
3800 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003801 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003802 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003803 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003804 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003805 case Stmt::CXXStaticCastExprClass:
3806 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003807 case Stmt::CXXConstCastExprClass:
3808 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003809 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3810 switch (cast<CastExpr>(E)->getCastKind()) {
3811 case CK_BitCast:
3812 case CK_LValueToRValue:
3813 case CK_NoOp:
3814 case CK_BaseToDerived:
3815 case CK_DerivedToBase:
3816 case CK_UncheckedDerivedToBase:
3817 case CK_Dynamic:
3818 case CK_CPointerToObjCPointerCast:
3819 case CK_BlockPointerToObjCPointerCast:
3820 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003821 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003822
3823 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003824 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003825
3826 default:
3827 return 0;
3828 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003829 }
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Douglas Gregor03e80032011-06-21 17:03:29 +00003831 case Stmt::MaterializeTemporaryExprClass:
3832 if (Expr *Result = EvalAddr(
3833 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003834 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003835 return Result;
3836
3837 return E;
3838
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003839 // Everything else: we simply don't reason about them.
3840 default:
3841 return NULL;
3842 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003843}
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Ted Kremenek06de2762007-08-17 16:46:58 +00003845
3846/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3847/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003848static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3849 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003850do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003851 // We should only be called for evaluating non-pointer expressions, or
3852 // expressions with a pointer type that are not used as references but instead
3853 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Ted Kremenek06de2762007-08-17 16:46:58 +00003855 // Our "symbolic interpreter" is just a dispatch off the currently
3856 // viewed AST node. We then recursively traverse the AST by calling
3857 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003858
3859 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003860 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003861 case Stmt::ImplicitCastExprClass: {
3862 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003863 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003864 E = IE->getSubExpr();
3865 continue;
3866 }
3867 return NULL;
3868 }
3869
John McCall80ee6e82011-11-10 05:35:25 +00003870 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003871 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003872
Douglas Gregora2813ce2009-10-23 18:54:35 +00003873 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003874 // When we hit a DeclRefExpr we are looking at code that refers to a
3875 // variable's name. If it's not a reference variable we check if it has
3876 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003877 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003879 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3880 // Check if it refers to itself, e.g. "int& i = i;".
3881 if (V == ParentDecl)
3882 return DR;
3883
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003884 if (V->hasLocalStorage()) {
3885 if (!V->getType()->isReferenceType())
3886 return DR;
3887
3888 // Reference variable, follow through to the expression that
3889 // it points to.
3890 if (V->hasInit()) {
3891 // Add the reference variable to the "trail".
3892 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003893 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003894 }
3895 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Ted Kremenek06de2762007-08-17 16:46:58 +00003898 return NULL;
3899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Ted Kremenek06de2762007-08-17 16:46:58 +00003901 case Stmt::UnaryOperatorClass: {
3902 // The only unary operator that make sense to handle here
3903 // is Deref. All others don't resolve to a "name." This includes
3904 // handling all sorts of rvalues passed to a unary operator.
3905 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003906
John McCall2de56d12010-08-25 11:45:40 +00003907 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003908 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003909
3910 return NULL;
3911 }
Mike Stump1eb44332009-09-09 15:08:12 +00003912
Ted Kremenek06de2762007-08-17 16:46:58 +00003913 case Stmt::ArraySubscriptExprClass: {
3914 // Array subscripts are potential references to data on the stack. We
3915 // retrieve the DeclRefExpr* for the array variable if it indeed
3916 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003917 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Ted Kremenek06de2762007-08-17 16:46:58 +00003920 case Stmt::ConditionalOperatorClass: {
3921 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003922 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003923 ConditionalOperator *C = cast<ConditionalOperator>(E);
3924
Anders Carlsson39073232007-11-30 19:04:31 +00003925 // Handle the GNU extension for missing LHS.
3926 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003927 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003928 return LHS;
3929
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003930 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003931 }
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Ted Kremenek06de2762007-08-17 16:46:58 +00003933 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003934 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003935 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003936
Ted Kremenek06de2762007-08-17 16:46:58 +00003937 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003938 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003939 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003940
3941 // Check whether the member type is itself a reference, in which case
3942 // we're not going to refer to the member, but to what the member refers to.
3943 if (M->getMemberDecl()->getType()->isReferenceType())
3944 return NULL;
3945
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003946 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003947 }
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Douglas Gregor03e80032011-06-21 17:03:29 +00003949 case Stmt::MaterializeTemporaryExprClass:
3950 if (Expr *Result = EvalVal(
3951 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003952 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003953 return Result;
3954
3955 return E;
3956
Ted Kremenek06de2762007-08-17 16:46:58 +00003957 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003958 // Check that we don't return or take the address of a reference to a
3959 // temporary. This is only useful in C++.
3960 if (!E->isTypeDependent() && E->isRValue())
3961 return E;
3962
3963 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003964 return NULL;
3965 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003966} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003967}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003968
3969//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3970
3971/// Check for comparisons of floating point operands using != and ==.
3972/// Issue a warning if these are no self-comparisons, as they are not likely
3973/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003974void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003975 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3976 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003977
3978 // Special case: check for x == x (which is OK).
3979 // Do not emit warnings for such cases.
3980 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3981 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3982 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003983 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
3985
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003986 // Special case: check for comparisons against literals that can be exactly
3987 // represented by APFloat. In such cases, do not emit a warning. This
3988 // is a heuristic: often comparison against such literals are used to
3989 // detect if a value in a variable has not changed. This clearly can
3990 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003991 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3992 if (FLL->isExact())
3993 return;
3994 } else
3995 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3996 if (FLR->isExact())
3997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003999 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004000 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4001 if (CL->isBuiltinCall())
4002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004003
David Blaikie980343b2012-07-16 20:47:22 +00004004 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4005 if (CR->isBuiltinCall())
4006 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004008 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004009 Diag(Loc, diag::warn_floatingpoint_eq)
4010 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004011}
John McCallba26e582010-01-04 23:21:16 +00004012
John McCallf2370c92010-01-06 05:24:50 +00004013//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4014//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004015
John McCallf2370c92010-01-06 05:24:50 +00004016namespace {
John McCallba26e582010-01-04 23:21:16 +00004017
John McCallf2370c92010-01-06 05:24:50 +00004018/// Structure recording the 'active' range of an integer-valued
4019/// expression.
4020struct IntRange {
4021 /// The number of bits active in the int.
4022 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004023
John McCallf2370c92010-01-06 05:24:50 +00004024 /// True if the int is known not to have negative values.
4025 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004026
John McCallf2370c92010-01-06 05:24:50 +00004027 IntRange(unsigned Width, bool NonNegative)
4028 : Width(Width), NonNegative(NonNegative)
4029 {}
John McCallba26e582010-01-04 23:21:16 +00004030
John McCall1844a6e2010-11-10 23:38:19 +00004031 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004032 static IntRange forBoolType() {
4033 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004034 }
4035
John McCall1844a6e2010-11-10 23:38:19 +00004036 /// Returns the range of an opaque value of the given integral type.
4037 static IntRange forValueOfType(ASTContext &C, QualType T) {
4038 return forValueOfCanonicalType(C,
4039 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004040 }
4041
John McCall1844a6e2010-11-10 23:38:19 +00004042 /// Returns the range of an opaque value of a canonical integral type.
4043 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004044 assert(T->isCanonicalUnqualified());
4045
4046 if (const VectorType *VT = dyn_cast<VectorType>(T))
4047 T = VT->getElementType().getTypePtr();
4048 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4049 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004050
David Majnemerf9eaf982013-06-07 22:07:20 +00004051 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004052 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004053 EnumDecl *Enum = ET->getDecl();
4054 if (!Enum->isCompleteDefinition())
4055 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004056
David Majnemerf9eaf982013-06-07 22:07:20 +00004057 unsigned NumPositive = Enum->getNumPositiveBits();
4058 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004059
David Majnemerf9eaf982013-06-07 22:07:20 +00004060 if (NumNegative == 0)
4061 return IntRange(NumPositive, true/*NonNegative*/);
4062 else
4063 return IntRange(std::max(NumPositive + 1, NumNegative),
4064 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004065 }
John McCallf2370c92010-01-06 05:24:50 +00004066
4067 const BuiltinType *BT = cast<BuiltinType>(T);
4068 assert(BT->isInteger());
4069
4070 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4071 }
4072
John McCall1844a6e2010-11-10 23:38:19 +00004073 /// Returns the "target" range of a canonical integral type, i.e.
4074 /// the range of values expressible in the type.
4075 ///
4076 /// This matches forValueOfCanonicalType except that enums have the
4077 /// full range of their type, not the range of their enumerators.
4078 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4079 assert(T->isCanonicalUnqualified());
4080
4081 if (const VectorType *VT = dyn_cast<VectorType>(T))
4082 T = VT->getElementType().getTypePtr();
4083 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4084 T = CT->getElementType().getTypePtr();
4085 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004086 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004087
4088 const BuiltinType *BT = cast<BuiltinType>(T);
4089 assert(BT->isInteger());
4090
4091 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4092 }
4093
4094 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004095 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004096 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004097 L.NonNegative && R.NonNegative);
4098 }
4099
John McCall1844a6e2010-11-10 23:38:19 +00004100 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004101 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004102 return IntRange(std::min(L.Width, R.Width),
4103 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004104 }
4105};
4106
Ted Kremenek0692a192012-01-31 05:37:37 +00004107static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4108 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004109 if (value.isSigned() && value.isNegative())
4110 return IntRange(value.getMinSignedBits(), false);
4111
4112 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004113 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004114
4115 // isNonNegative() just checks the sign bit without considering
4116 // signedness.
4117 return IntRange(value.getActiveBits(), true);
4118}
4119
Ted Kremenek0692a192012-01-31 05:37:37 +00004120static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4121 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004122 if (result.isInt())
4123 return GetValueRange(C, result.getInt(), MaxWidth);
4124
4125 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004126 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4127 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4128 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4129 R = IntRange::join(R, El);
4130 }
John McCallf2370c92010-01-06 05:24:50 +00004131 return R;
4132 }
4133
4134 if (result.isComplexInt()) {
4135 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4136 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4137 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004138 }
4139
4140 // This can happen with lossless casts to intptr_t of "based" lvalues.
4141 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004142 // FIXME: The only reason we need to pass the type in here is to get
4143 // the sign right on this one case. It would be nice if APValue
4144 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004145 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004146 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004147}
John McCallf2370c92010-01-06 05:24:50 +00004148
4149/// Pseudo-evaluate the given integer expression, estimating the
4150/// range of values it might take.
4151///
4152/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004153static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004154 E = E->IgnoreParens();
4155
4156 // Try a full evaluation first.
4157 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004158 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004159 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004160
4161 // I think we only want to look through implicit casts here; if the
4162 // user has an explicit widening cast, we should treat the value as
4163 // being of the new, wider type.
4164 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004165 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004166 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4167
John McCall1844a6e2010-11-10 23:38:19 +00004168 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004169
John McCall2de56d12010-08-25 11:45:40 +00004170 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004171
John McCallf2370c92010-01-06 05:24:50 +00004172 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004173 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004174 return OutputTypeRange;
4175
4176 IntRange SubRange
4177 = GetExprRange(C, CE->getSubExpr(),
4178 std::min(MaxWidth, OutputTypeRange.Width));
4179
4180 // Bail out if the subexpr's range is as wide as the cast type.
4181 if (SubRange.Width >= OutputTypeRange.Width)
4182 return OutputTypeRange;
4183
4184 // Otherwise, we take the smaller width, and we're non-negative if
4185 // either the output type or the subexpr is.
4186 return IntRange(SubRange.Width,
4187 SubRange.NonNegative || OutputTypeRange.NonNegative);
4188 }
4189
4190 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4191 // If we can fold the condition, just take that operand.
4192 bool CondResult;
4193 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4194 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4195 : CO->getFalseExpr(),
4196 MaxWidth);
4197
4198 // Otherwise, conservatively merge.
4199 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4200 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4201 return IntRange::join(L, R);
4202 }
4203
4204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4205 switch (BO->getOpcode()) {
4206
4207 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004208 case BO_LAnd:
4209 case BO_LOr:
4210 case BO_LT:
4211 case BO_GT:
4212 case BO_LE:
4213 case BO_GE:
4214 case BO_EQ:
4215 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004216 return IntRange::forBoolType();
4217
John McCall862ff872011-07-13 06:35:24 +00004218 // The type of the assignments is the type of the LHS, so the RHS
4219 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004220 case BO_MulAssign:
4221 case BO_DivAssign:
4222 case BO_RemAssign:
4223 case BO_AddAssign:
4224 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004225 case BO_XorAssign:
4226 case BO_OrAssign:
4227 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004228 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004229
John McCall862ff872011-07-13 06:35:24 +00004230 // Simple assignments just pass through the RHS, which will have
4231 // been coerced to the LHS type.
4232 case BO_Assign:
4233 // TODO: bitfields?
4234 return GetExprRange(C, BO->getRHS(), MaxWidth);
4235
John McCallf2370c92010-01-06 05:24:50 +00004236 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004237 case BO_PtrMemD:
4238 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004239 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004240
John McCall60fad452010-01-06 22:07:33 +00004241 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004242 case BO_And:
4243 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004244 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4245 GetExprRange(C, BO->getRHS(), MaxWidth));
4246
John McCallf2370c92010-01-06 05:24:50 +00004247 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004248 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004249 // ...except that we want to treat '1 << (blah)' as logically
4250 // positive. It's an important idiom.
4251 if (IntegerLiteral *I
4252 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4253 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004254 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004255 return IntRange(R.Width, /*NonNegative*/ true);
4256 }
4257 }
4258 // fallthrough
4259
John McCall2de56d12010-08-25 11:45:40 +00004260 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004261 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004262
John McCall60fad452010-01-06 22:07:33 +00004263 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004264 case BO_Shr:
4265 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004266 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4267
4268 // If the shift amount is a positive constant, drop the width by
4269 // that much.
4270 llvm::APSInt shift;
4271 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4272 shift.isNonNegative()) {
4273 unsigned zext = shift.getZExtValue();
4274 if (zext >= L.Width)
4275 L.Width = (L.NonNegative ? 0 : 1);
4276 else
4277 L.Width -= zext;
4278 }
4279
4280 return L;
4281 }
4282
4283 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004284 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004285 return GetExprRange(C, BO->getRHS(), MaxWidth);
4286
John McCall60fad452010-01-06 22:07:33 +00004287 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004288 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004289 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004290 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004291 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004292
John McCall00fe7612011-07-14 22:39:48 +00004293 // The width of a division result is mostly determined by the size
4294 // of the LHS.
4295 case BO_Div: {
4296 // Don't 'pre-truncate' the operands.
4297 unsigned opWidth = C.getIntWidth(E->getType());
4298 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4299
4300 // If the divisor is constant, use that.
4301 llvm::APSInt divisor;
4302 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4303 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4304 if (log2 >= L.Width)
4305 L.Width = (L.NonNegative ? 0 : 1);
4306 else
4307 L.Width = std::min(L.Width - log2, MaxWidth);
4308 return L;
4309 }
4310
4311 // Otherwise, just use the LHS's width.
4312 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4313 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4314 }
4315
4316 // The result of a remainder can't be larger than the result of
4317 // either side.
4318 case BO_Rem: {
4319 // Don't 'pre-truncate' the operands.
4320 unsigned opWidth = C.getIntWidth(E->getType());
4321 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4322 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4323
4324 IntRange meet = IntRange::meet(L, R);
4325 meet.Width = std::min(meet.Width, MaxWidth);
4326 return meet;
4327 }
4328
4329 // The default behavior is okay for these.
4330 case BO_Mul:
4331 case BO_Add:
4332 case BO_Xor:
4333 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004334 break;
4335 }
4336
John McCall00fe7612011-07-14 22:39:48 +00004337 // The default case is to treat the operation as if it were closed
4338 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004339 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4340 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4341 return IntRange::join(L, R);
4342 }
4343
4344 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4345 switch (UO->getOpcode()) {
4346 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004347 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004348 return IntRange::forBoolType();
4349
4350 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004351 case UO_Deref:
4352 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004353 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004354
4355 default:
4356 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4357 }
4358 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004359
4360 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004361 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004362 }
John McCallf2370c92010-01-06 05:24:50 +00004363
John McCall993f43f2013-05-06 21:39:12 +00004364 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004365 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004366 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004367
John McCall1844a6e2010-11-10 23:38:19 +00004368 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004369}
John McCall51313c32010-01-04 23:31:57 +00004370
Ted Kremenek0692a192012-01-31 05:37:37 +00004371static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004372 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4373}
4374
John McCall51313c32010-01-04 23:31:57 +00004375/// Checks whether the given value, which currently has the given
4376/// source semantics, has the same value when coerced through the
4377/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004378static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4379 const llvm::fltSemantics &Src,
4380 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004381 llvm::APFloat truncated = value;
4382
4383 bool ignored;
4384 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4385 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4386
4387 return truncated.bitwiseIsEqual(value);
4388}
4389
4390/// Checks whether the given value, which currently has the given
4391/// source semantics, has the same value when coerced through the
4392/// target semantics.
4393///
4394/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004395static bool IsSameFloatAfterCast(const APValue &value,
4396 const llvm::fltSemantics &Src,
4397 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004398 if (value.isFloat())
4399 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4400
4401 if (value.isVector()) {
4402 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4403 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4404 return false;
4405 return true;
4406 }
4407
4408 assert(value.isComplexFloat());
4409 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4410 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4411}
4412
Ted Kremenek0692a192012-01-31 05:37:37 +00004413static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004414
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004415static bool IsZero(Sema &S, Expr *E) {
4416 // Suppress cases where we are comparing against an enum constant.
4417 if (const DeclRefExpr *DR =
4418 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4419 if (isa<EnumConstantDecl>(DR->getDecl()))
4420 return false;
4421
4422 // Suppress cases where the '0' value is expanded from a macro.
4423 if (E->getLocStart().isMacroID())
4424 return false;
4425
John McCall323ed742010-05-06 08:58:33 +00004426 llvm::APSInt Value;
4427 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4428}
4429
John McCall372e1032010-10-06 00:25:24 +00004430static bool HasEnumType(Expr *E) {
4431 // Strip off implicit integral promotions.
4432 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004433 if (ICE->getCastKind() != CK_IntegralCast &&
4434 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004435 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004436 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004437 }
4438
4439 return E->getType()->isEnumeralType();
4440}
4441
Ted Kremenek0692a192012-01-31 05:37:37 +00004442static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004443 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004444 if (E->isValueDependent())
4445 return;
4446
John McCall2de56d12010-08-25 11:45:40 +00004447 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004448 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004449 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004450 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004451 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004452 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004453 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004454 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004455 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004456 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004457 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004458 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004459 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004460 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004461 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004462 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4463 }
4464}
4465
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004466static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004467 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004468 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004469 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004470 // 0 values are handled later by CheckTrivialUnsignedComparison().
4471 if (Value == 0)
4472 return;
4473
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004474 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004475 QualType OtherT = Other->getType();
4476 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004477 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004478 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004479 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004480 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004481 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004482
4483 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004484 bool CommonSigned = CommonT->isSignedIntegerType();
4485
4486 bool EqualityOnly = false;
4487
4488 // TODO: Investigate using GetExprRange() to get tighter bounds on
4489 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004490 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004491 unsigned OtherWidth = OtherRange.Width;
4492
4493 if (CommonSigned) {
4494 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004495 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004496 // Check that the constant is representable in type OtherT.
4497 if (ConstantSigned) {
4498 if (OtherWidth >= Value.getMinSignedBits())
4499 return;
4500 } else { // !ConstantSigned
4501 if (OtherWidth >= Value.getActiveBits() + 1)
4502 return;
4503 }
4504 } else { // !OtherSigned
4505 // Check that the constant is representable in type OtherT.
4506 // Negative values are out of range.
4507 if (ConstantSigned) {
4508 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4509 return;
4510 } else { // !ConstantSigned
4511 if (OtherWidth >= Value.getActiveBits())
4512 return;
4513 }
4514 }
4515 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004516 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004517 if (OtherWidth >= Value.getActiveBits())
4518 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004519 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004520 // Check to see if the constant is representable in OtherT.
4521 if (OtherWidth > Value.getActiveBits())
4522 return;
4523 // Check to see if the constant is equivalent to a negative value
4524 // cast to CommonT.
4525 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004526 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004527 return;
4528 // The constant value rests between values that OtherT can represent after
4529 // conversion. Relational comparison still works, but equality
4530 // comparisons will be tautological.
4531 EqualityOnly = true;
4532 } else { // OtherSigned && ConstantSigned
4533 assert(0 && "Two signed types converted to unsigned types.");
4534 }
4535 }
4536
4537 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4538
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004539 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004540 if (op == BO_EQ || op == BO_NE) {
4541 IsTrue = op == BO_NE;
4542 } else if (EqualityOnly) {
4543 return;
4544 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004545 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004546 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004547 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004548 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004549 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004550 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004551 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004552 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004553 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004554 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004555
4556 // If this is a comparison to an enum constant, include that
4557 // constant in the diagnostic.
4558 const EnumConstantDecl *ED = 0;
4559 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4560 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4561
4562 SmallString<64> PrettySourceValue;
4563 llvm::raw_svector_ostream OS(PrettySourceValue);
4564 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004565 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004566 else
4567 OS << Value;
4568
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004569 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004570 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004571 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004572}
4573
John McCall323ed742010-05-06 08:58:33 +00004574/// Analyze the operands of the given comparison. Implements the
4575/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004576static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004577 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4578 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004579}
John McCall51313c32010-01-04 23:31:57 +00004580
John McCallba26e582010-01-04 23:21:16 +00004581/// \brief Implements -Wsign-compare.
4582///
Richard Trieudd225092011-09-15 21:56:47 +00004583/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004584static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004585 // The type the comparison is being performed in.
4586 QualType T = E->getLHS()->getType();
4587 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4588 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004589 if (E->isValueDependent())
4590 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004591
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004592 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4593 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004594
4595 bool IsComparisonConstant = false;
4596
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004597 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004598 // of 'true' or 'false'.
4599 if (T->isIntegralType(S.Context)) {
4600 llvm::APSInt RHSValue;
4601 bool IsRHSIntegralLiteral =
4602 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4603 llvm::APSInt LHSValue;
4604 bool IsLHSIntegralLiteral =
4605 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4606 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4607 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4608 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4609 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4610 else
4611 IsComparisonConstant =
4612 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004613 } else if (!T->hasUnsignedIntegerRepresentation())
4614 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004615
John McCall323ed742010-05-06 08:58:33 +00004616 // We don't do anything special if this isn't an unsigned integral
4617 // comparison: we're only interested in integral comparisons, and
4618 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004619 //
4620 // We also don't care about value-dependent expressions or expressions
4621 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004622 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004623 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004624
John McCall323ed742010-05-06 08:58:33 +00004625 // Check to see if one of the (unmodified) operands is of different
4626 // signedness.
4627 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004628 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4629 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004630 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004631 signedOperand = LHS;
4632 unsignedOperand = RHS;
4633 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4634 signedOperand = RHS;
4635 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004636 } else {
John McCall323ed742010-05-06 08:58:33 +00004637 CheckTrivialUnsignedComparison(S, E);
4638 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004639 }
4640
John McCall323ed742010-05-06 08:58:33 +00004641 // Otherwise, calculate the effective range of the signed operand.
4642 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004643
John McCall323ed742010-05-06 08:58:33 +00004644 // Go ahead and analyze implicit conversions in the operands. Note
4645 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004646 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4647 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004648
John McCall323ed742010-05-06 08:58:33 +00004649 // If the signed range is non-negative, -Wsign-compare won't fire,
4650 // but we should still check for comparisons which are always true
4651 // or false.
4652 if (signedRange.NonNegative)
4653 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004654
4655 // For (in)equality comparisons, if the unsigned operand is a
4656 // constant which cannot collide with a overflowed signed operand,
4657 // then reinterpreting the signed operand as unsigned will not
4658 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004659 if (E->isEqualityOp()) {
4660 unsigned comparisonWidth = S.Context.getIntWidth(T);
4661 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004662
John McCall323ed742010-05-06 08:58:33 +00004663 // We should never be unable to prove that the unsigned operand is
4664 // non-negative.
4665 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4666
4667 if (unsignedRange.Width < comparisonWidth)
4668 return;
4669 }
4670
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004671 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4672 S.PDiag(diag::warn_mixed_sign_comparison)
4673 << LHS->getType() << RHS->getType()
4674 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004675}
4676
John McCall15d7d122010-11-11 03:21:53 +00004677/// Analyzes an attempt to assign the given value to a bitfield.
4678///
4679/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004680static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4681 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004682 assert(Bitfield->isBitField());
4683 if (Bitfield->isInvalidDecl())
4684 return false;
4685
John McCall91b60142010-11-11 05:33:51 +00004686 // White-list bool bitfields.
4687 if (Bitfield->getType()->isBooleanType())
4688 return false;
4689
Douglas Gregor46ff3032011-02-04 13:09:01 +00004690 // Ignore value- or type-dependent expressions.
4691 if (Bitfield->getBitWidth()->isValueDependent() ||
4692 Bitfield->getBitWidth()->isTypeDependent() ||
4693 Init->isValueDependent() ||
4694 Init->isTypeDependent())
4695 return false;
4696
John McCall15d7d122010-11-11 03:21:53 +00004697 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4698
Richard Smith80d4b552011-12-28 19:48:30 +00004699 llvm::APSInt Value;
4700 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004701 return false;
4702
John McCall15d7d122010-11-11 03:21:53 +00004703 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004704 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004705
4706 if (OriginalWidth <= FieldWidth)
4707 return false;
4708
Eli Friedman3a643af2012-01-26 23:11:39 +00004709 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004710 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004711 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004712
Eli Friedman3a643af2012-01-26 23:11:39 +00004713 // Check whether the stored value is equal to the original value.
4714 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004715 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004716 return false;
4717
Eli Friedman3a643af2012-01-26 23:11:39 +00004718 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004719 // therefore don't strictly fit into a signed bitfield of width 1.
4720 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004721 return false;
4722
John McCall15d7d122010-11-11 03:21:53 +00004723 std::string PrettyValue = Value.toString(10);
4724 std::string PrettyTrunc = TruncatedValue.toString(10);
4725
4726 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4727 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4728 << Init->getSourceRange();
4729
4730 return true;
4731}
4732
John McCallbeb22aa2010-11-09 23:24:47 +00004733/// Analyze the given simple or compound assignment for warning-worthy
4734/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004735static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004736 // Just recurse on the LHS.
4737 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4738
4739 // We want to recurse on the RHS as normal unless we're assigning to
4740 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004741 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004742 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004743 E->getOperatorLoc())) {
4744 // Recurse, ignoring any implicit conversions on the RHS.
4745 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4746 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004747 }
4748 }
4749
4750 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4751}
4752
John McCall51313c32010-01-04 23:31:57 +00004753/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004754static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004755 SourceLocation CContext, unsigned diag,
4756 bool pruneControlFlow = false) {
4757 if (pruneControlFlow) {
4758 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4759 S.PDiag(diag)
4760 << SourceType << T << E->getSourceRange()
4761 << SourceRange(CContext));
4762 return;
4763 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004764 S.Diag(E->getExprLoc(), diag)
4765 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4766}
4767
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004768/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004769static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004770 SourceLocation CContext, unsigned diag,
4771 bool pruneControlFlow = false) {
4772 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004773}
4774
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004775/// Diagnose an implicit cast from a literal expression. Does not warn when the
4776/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004777void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4778 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004779 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004780 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004781 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004782 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4783 T->hasUnsignedIntegerRepresentation());
4784 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004785 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004786 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004787 return;
4788
David Blaikiebe0ee872012-05-15 16:56:36 +00004789 SmallString<16> PrettySourceValue;
4790 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004791 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004792 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4793 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4794 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004795 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004796
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004797 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004798 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4799 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004800}
4801
John McCall091f23f2010-11-09 22:22:12 +00004802std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4803 if (!Range.Width) return "0";
4804
4805 llvm::APSInt ValueInRange = Value;
4806 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004807 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004808 return ValueInRange.toString(10);
4809}
4810
Hans Wennborg88617a22012-08-28 15:44:30 +00004811static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4812 if (!isa<ImplicitCastExpr>(Ex))
4813 return false;
4814
4815 Expr *InnerE = Ex->IgnoreParenImpCasts();
4816 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4817 const Type *Source =
4818 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4819 if (Target->isDependentType())
4820 return false;
4821
4822 const BuiltinType *FloatCandidateBT =
4823 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4824 const Type *BoolCandidateType = ToBool ? Target : Source;
4825
4826 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4827 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4828}
4829
4830void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4831 SourceLocation CC) {
4832 unsigned NumArgs = TheCall->getNumArgs();
4833 for (unsigned i = 0; i < NumArgs; ++i) {
4834 Expr *CurrA = TheCall->getArg(i);
4835 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4836 continue;
4837
4838 bool IsSwapped = ((i > 0) &&
4839 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4840 IsSwapped |= ((i < (NumArgs - 1)) &&
4841 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4842 if (IsSwapped) {
4843 // Warn on this floating-point to bool conversion.
4844 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4845 CurrA->getType(), CC,
4846 diag::warn_impcast_floating_point_to_bool);
4847 }
4848 }
4849}
4850
John McCall323ed742010-05-06 08:58:33 +00004851void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004852 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004853 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004854
John McCall323ed742010-05-06 08:58:33 +00004855 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4856 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4857 if (Source == Target) return;
4858 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004859
Chandler Carruth108f7562011-07-26 05:40:03 +00004860 // If the conversion context location is invalid don't complain. We also
4861 // don't want to emit a warning if the issue occurs from the expansion of
4862 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4863 // delay this check as long as possible. Once we detect we are in that
4864 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004865 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004866 return;
4867
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004868 // Diagnose implicit casts to bool.
4869 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4870 if (isa<StringLiteral>(E))
4871 // Warn on string literal to bool. Checks for string literals in logical
4872 // expressions, for instances, assert(0 && "error here"), is prevented
4873 // by a check in AnalyzeImplicitConversions().
4874 return DiagnoseImpCast(S, E, T, CC,
4875 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004876 if (Source->isFunctionType()) {
4877 // Warn on function to bool. Checks free functions and static member
4878 // functions. Weakly imported functions are excluded from the check,
4879 // since it's common to test their value to check whether the linker
4880 // found a definition for them.
4881 ValueDecl *D = 0;
4882 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4883 D = R->getDecl();
4884 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4885 D = M->getMemberDecl();
4886 }
4887
4888 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004889 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4890 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4891 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004892 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4893 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4894 QualType ReturnType;
4895 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00004896 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00004897 if (!ReturnType.isNull()
4898 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4899 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4900 << FixItHint::CreateInsertion(
4901 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004902 return;
4903 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004904 }
4905 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004906 }
John McCall51313c32010-01-04 23:31:57 +00004907
4908 // Strip vector types.
4909 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004910 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004911 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004912 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004913 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004914 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004915
4916 // If the vector cast is cast between two vectors of the same size, it is
4917 // a bitcast, not a conversion.
4918 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4919 return;
John McCall51313c32010-01-04 23:31:57 +00004920
4921 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4922 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4923 }
4924
4925 // Strip complex types.
4926 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004927 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004928 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004929 return;
4930
John McCallb4eb64d2010-10-08 02:01:28 +00004931 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004932 }
John McCall51313c32010-01-04 23:31:57 +00004933
4934 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4935 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4936 }
4937
4938 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4939 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4940
4941 // If the source is floating point...
4942 if (SourceBT && SourceBT->isFloatingPoint()) {
4943 // ...and the target is floating point...
4944 if (TargetBT && TargetBT->isFloatingPoint()) {
4945 // ...then warn if we're dropping FP rank.
4946
4947 // Builtin FP kinds are ordered by increasing FP rank.
4948 if (SourceBT->getKind() > TargetBT->getKind()) {
4949 // Don't warn about float constants that are precisely
4950 // representable in the target type.
4951 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004952 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004953 // Value might be a float, a float vector, or a float complex.
4954 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004955 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4956 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004957 return;
4958 }
4959
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004960 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004961 return;
4962
John McCallb4eb64d2010-10-08 02:01:28 +00004963 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004964 }
4965 return;
4966 }
4967
Ted Kremenekef9ff882011-03-10 20:03:42 +00004968 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004969 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004970 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004971 return;
4972
Chandler Carrutha5b93322011-02-17 11:05:49 +00004973 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004974 // We also want to warn on, e.g., "int i = -1.234"
4975 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4976 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4977 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4978
Chandler Carruthf65076e2011-04-10 08:36:24 +00004979 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4980 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004981 } else {
4982 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4983 }
4984 }
John McCall51313c32010-01-04 23:31:57 +00004985
Hans Wennborg88617a22012-08-28 15:44:30 +00004986 // If the target is bool, warn if expr is a function or method call.
4987 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4988 isa<CallExpr>(E)) {
4989 // Check last argument of function call to see if it is an
4990 // implicit cast from a type matching the type the result
4991 // is being cast to.
4992 CallExpr *CEx = cast<CallExpr>(E);
4993 unsigned NumArgs = CEx->getNumArgs();
4994 if (NumArgs > 0) {
4995 Expr *LastA = CEx->getArg(NumArgs - 1);
4996 Expr *InnerE = LastA->IgnoreParenImpCasts();
4997 const Type *InnerType =
4998 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4999 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5000 // Warn on this floating-point to bool conversion
5001 DiagnoseImpCast(S, E, T, CC,
5002 diag::warn_impcast_floating_point_to_bool);
5003 }
5004 }
5005 }
John McCall51313c32010-01-04 23:31:57 +00005006 return;
5007 }
5008
Richard Trieu1838ca52011-05-29 19:59:02 +00005009 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005010 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005011 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005012 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005013 SourceLocation Loc = E->getSourceRange().getBegin();
5014 if (Loc.isMacroID())
5015 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005016 if (!Loc.isMacroID() || CC.isMacroID())
5017 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5018 << T << clang::SourceRange(CC)
5019 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005020 }
5021
David Blaikieb26331b2012-06-19 21:19:06 +00005022 if (!Source->isIntegerType() || !Target->isIntegerType())
5023 return;
5024
David Blaikiebe0ee872012-05-15 16:56:36 +00005025 // TODO: remove this early return once the false positives for constant->bool
5026 // in templates, macros, etc, are reduced or removed.
5027 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5028 return;
5029
John McCall323ed742010-05-06 08:58:33 +00005030 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005031 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005032
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005033 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005034 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005035 // TODO: this should happen for bitfield stores, too.
5036 llvm::APSInt Value(32);
5037 if (E->isIntegerConstantExpr(Value, S.Context)) {
5038 if (S.SourceMgr.isInSystemMacro(CC))
5039 return;
5040
John McCall091f23f2010-11-09 22:22:12 +00005041 std::string PrettySourceValue = Value.toString(10);
5042 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005043
Ted Kremenek5e745da2011-10-22 02:37:33 +00005044 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5045 S.PDiag(diag::warn_impcast_integer_precision_constant)
5046 << PrettySourceValue << PrettyTargetValue
5047 << E->getType() << T << E->getSourceRange()
5048 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005049 return;
5050 }
5051
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005052 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5053 if (S.SourceMgr.isInSystemMacro(CC))
5054 return;
5055
David Blaikie37050842012-04-12 22:40:54 +00005056 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005057 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5058 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005059 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005060 }
5061
5062 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5063 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5064 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005065
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005066 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005067 return;
5068
John McCall323ed742010-05-06 08:58:33 +00005069 unsigned DiagID = diag::warn_impcast_integer_sign;
5070
5071 // Traditionally, gcc has warned about this under -Wsign-compare.
5072 // We also want to warn about it in -Wconversion.
5073 // So if -Wconversion is off, use a completely identical diagnostic
5074 // in the sign-compare group.
5075 // The conditional-checking code will
5076 if (ICContext) {
5077 DiagID = diag::warn_impcast_integer_sign_conditional;
5078 *ICContext = true;
5079 }
5080
John McCallb4eb64d2010-10-08 02:01:28 +00005081 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005082 }
5083
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005084 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005085 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5086 // type, to give us better diagnostics.
5087 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005088 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5090 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5091 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5092 SourceType = S.Context.getTypeDeclType(Enum);
5093 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5094 }
5095 }
5096
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005097 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5098 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005099 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5100 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005101 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005102 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005103 return;
5104
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005105 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005106 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005107 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005108
John McCall51313c32010-01-04 23:31:57 +00005109 return;
5110}
5111
David Blaikie9fb1ac52012-05-15 21:57:38 +00005112void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5113 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005114
5115void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005116 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005117 E = E->IgnoreParenImpCasts();
5118
5119 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005120 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005121
John McCallb4eb64d2010-10-08 02:01:28 +00005122 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005123 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005124 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005125 return;
5126}
5127
David Blaikie9fb1ac52012-05-15 21:57:38 +00005128void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5129 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005130 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005131
5132 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005133 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5134 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005135
5136 // If -Wconversion would have warned about either of the candidates
5137 // for a signedness conversion to the context type...
5138 if (!Suspicious) return;
5139
5140 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005141 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5142 CC))
John McCall323ed742010-05-06 08:58:33 +00005143 return;
5144
John McCall323ed742010-05-06 08:58:33 +00005145 // ...then check whether it would have warned about either of the
5146 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005147 if (E->getType() == T) return;
5148
5149 Suspicious = false;
5150 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5151 E->getType(), CC, &Suspicious);
5152 if (!Suspicious)
5153 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005154 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005155}
5156
5157/// AnalyzeImplicitConversions - Find and report any interesting
5158/// implicit conversions in the given expression. There are a couple
5159/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005160void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005161 QualType T = OrigE->getType();
5162 Expr *E = OrigE->IgnoreParenImpCasts();
5163
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005164 if (E->isTypeDependent() || E->isValueDependent())
5165 return;
5166
John McCall323ed742010-05-06 08:58:33 +00005167 // For conditional operators, we analyze the arguments as if they
5168 // were being fed directly into the output.
5169 if (isa<ConditionalOperator>(E)) {
5170 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005171 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005172 return;
5173 }
5174
Hans Wennborg88617a22012-08-28 15:44:30 +00005175 // Check implicit argument conversions for function calls.
5176 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5177 CheckImplicitArgumentConversions(S, Call, CC);
5178
John McCall323ed742010-05-06 08:58:33 +00005179 // Go ahead and check any implicit conversions we might have skipped.
5180 // The non-canonical typecheck is just an optimization;
5181 // CheckImplicitConversion will filter out dead implicit conversions.
5182 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005183 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005184
5185 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005186
5187 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005188 if (POE->getResultExpr())
5189 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005190 }
5191
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005192 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5193 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5194
John McCall323ed742010-05-06 08:58:33 +00005195 // Skip past explicit casts.
5196 if (isa<ExplicitCastExpr>(E)) {
5197 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005198 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005199 }
5200
John McCallbeb22aa2010-11-09 23:24:47 +00005201 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5202 // Do a somewhat different check with comparison operators.
5203 if (BO->isComparisonOp())
5204 return AnalyzeComparison(S, BO);
5205
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005206 // And with simple assignments.
5207 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005208 return AnalyzeAssignment(S, BO);
5209 }
John McCall323ed742010-05-06 08:58:33 +00005210
5211 // These break the otherwise-useful invariant below. Fortunately,
5212 // we don't really need to recurse into them, because any internal
5213 // expressions should have been analyzed already when they were
5214 // built into statements.
5215 if (isa<StmtExpr>(E)) return;
5216
5217 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005218 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005219
5220 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005221 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005222 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5223 bool IsLogicalOperator = BO && BO->isLogicalOp();
5224 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005225 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005226 if (!ChildExpr)
5227 continue;
5228
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005229 if (IsLogicalOperator &&
5230 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5231 // Ignore checking string literals that are in logical operators.
5232 continue;
5233 AnalyzeImplicitConversions(S, ChildExpr, CC);
5234 }
John McCall323ed742010-05-06 08:58:33 +00005235}
5236
5237} // end anonymous namespace
5238
5239/// Diagnoses "dangerous" implicit conversions within the given
5240/// expression (which is a full expression). Implements -Wconversion
5241/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005242///
5243/// \param CC the "context" location of the implicit conversion, i.e.
5244/// the most location of the syntactic entity requiring the implicit
5245/// conversion
5246void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005247 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005248 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005249 return;
5250
5251 // Don't diagnose for value- or type-dependent expressions.
5252 if (E->isTypeDependent() || E->isValueDependent())
5253 return;
5254
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005255 // Check for array bounds violations in cases where the check isn't triggered
5256 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5257 // ArraySubscriptExpr is on the RHS of a variable initialization.
5258 CheckArrayAccess(E);
5259
John McCallb4eb64d2010-10-08 02:01:28 +00005260 // This is not the right CC for (e.g.) a variable initialization.
5261 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005262}
5263
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005264/// Diagnose when expression is an integer constant expression and its evaluation
5265/// results in integer overflow
5266void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005267 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005268 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5269 E->EvaluateForOverflow(Context, &Diags);
5270 }
5271}
5272
Richard Smith6c3af3d2013-01-17 01:17:56 +00005273namespace {
5274/// \brief Visitor for expressions which looks for unsequenced operations on the
5275/// same object.
5276class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005277 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5278
Richard Smith6c3af3d2013-01-17 01:17:56 +00005279 /// \brief A tree of sequenced regions within an expression. Two regions are
5280 /// unsequenced if one is an ancestor or a descendent of the other. When we
5281 /// finish processing an expression with sequencing, such as a comma
5282 /// expression, we fold its tree nodes into its parent, since they are
5283 /// unsequenced with respect to nodes we will visit later.
5284 class SequenceTree {
5285 struct Value {
5286 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5287 unsigned Parent : 31;
5288 bool Merged : 1;
5289 };
5290 llvm::SmallVector<Value, 8> Values;
5291
5292 public:
5293 /// \brief A region within an expression which may be sequenced with respect
5294 /// to some other region.
5295 class Seq {
5296 explicit Seq(unsigned N) : Index(N) {}
5297 unsigned Index;
5298 friend class SequenceTree;
5299 public:
5300 Seq() : Index(0) {}
5301 };
5302
5303 SequenceTree() { Values.push_back(Value(0)); }
5304 Seq root() const { return Seq(0); }
5305
5306 /// \brief Create a new sequence of operations, which is an unsequenced
5307 /// subset of \p Parent. This sequence of operations is sequenced with
5308 /// respect to other children of \p Parent.
5309 Seq allocate(Seq Parent) {
5310 Values.push_back(Value(Parent.Index));
5311 return Seq(Values.size() - 1);
5312 }
5313
5314 /// \brief Merge a sequence of operations into its parent.
5315 void merge(Seq S) {
5316 Values[S.Index].Merged = true;
5317 }
5318
5319 /// \brief Determine whether two operations are unsequenced. This operation
5320 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5321 /// should have been merged into its parent as appropriate.
5322 bool isUnsequenced(Seq Cur, Seq Old) {
5323 unsigned C = representative(Cur.Index);
5324 unsigned Target = representative(Old.Index);
5325 while (C >= Target) {
5326 if (C == Target)
5327 return true;
5328 C = Values[C].Parent;
5329 }
5330 return false;
5331 }
5332
5333 private:
5334 /// \brief Pick a representative for a sequence.
5335 unsigned representative(unsigned K) {
5336 if (Values[K].Merged)
5337 // Perform path compression as we go.
5338 return Values[K].Parent = representative(Values[K].Parent);
5339 return K;
5340 }
5341 };
5342
5343 /// An object for which we can track unsequenced uses.
5344 typedef NamedDecl *Object;
5345
5346 /// Different flavors of object usage which we track. We only track the
5347 /// least-sequenced usage of each kind.
5348 enum UsageKind {
5349 /// A read of an object. Multiple unsequenced reads are OK.
5350 UK_Use,
5351 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005352 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005353 UK_ModAsValue,
5354 /// A modification of an object which is not sequenced before the value
5355 /// computation of the expression, such as n++.
5356 UK_ModAsSideEffect,
5357
5358 UK_Count = UK_ModAsSideEffect + 1
5359 };
5360
5361 struct Usage {
5362 Usage() : Use(0), Seq() {}
5363 Expr *Use;
5364 SequenceTree::Seq Seq;
5365 };
5366
5367 struct UsageInfo {
5368 UsageInfo() : Diagnosed(false) {}
5369 Usage Uses[UK_Count];
5370 /// Have we issued a diagnostic for this variable already?
5371 bool Diagnosed;
5372 };
5373 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5374
5375 Sema &SemaRef;
5376 /// Sequenced regions within the expression.
5377 SequenceTree Tree;
5378 /// Declaration modifications and references which we have seen.
5379 UsageInfoMap UsageMap;
5380 /// The region we are currently within.
5381 SequenceTree::Seq Region;
5382 /// Filled in with declarations which were modified as a side-effect
5383 /// (that is, post-increment operations).
5384 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005385 /// Expressions to check later. We defer checking these to reduce
5386 /// stack usage.
5387 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005388
5389 /// RAII object wrapping the visitation of a sequenced subexpression of an
5390 /// expression. At the end of this process, the side-effects of the evaluation
5391 /// become sequenced with respect to the value computation of the result, so
5392 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5393 /// UK_ModAsValue.
5394 struct SequencedSubexpression {
5395 SequencedSubexpression(SequenceChecker &Self)
5396 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5397 Self.ModAsSideEffect = &ModAsSideEffect;
5398 }
5399 ~SequencedSubexpression() {
5400 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5401 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5402 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5403 Self.addUsage(U, ModAsSideEffect[I].first,
5404 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5405 }
5406 Self.ModAsSideEffect = OldModAsSideEffect;
5407 }
5408
5409 SequenceChecker &Self;
5410 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5411 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5412 };
5413
Richard Smith67470052013-06-20 22:21:56 +00005414 /// RAII object wrapping the visitation of a subexpression which we might
5415 /// choose to evaluate as a constant. If any subexpression is evaluated and
5416 /// found to be non-constant, this allows us to suppress the evaluation of
5417 /// the outer expression.
5418 class EvaluationTracker {
5419 public:
5420 EvaluationTracker(SequenceChecker &Self)
5421 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5422 Self.EvalTracker = this;
5423 }
5424 ~EvaluationTracker() {
5425 Self.EvalTracker = Prev;
5426 if (Prev)
5427 Prev->EvalOK &= EvalOK;
5428 }
5429
5430 bool evaluate(const Expr *E, bool &Result) {
5431 if (!EvalOK || E->isValueDependent())
5432 return false;
5433 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5434 return EvalOK;
5435 }
5436
5437 private:
5438 SequenceChecker &Self;
5439 EvaluationTracker *Prev;
5440 bool EvalOK;
5441 } *EvalTracker;
5442
Richard Smith6c3af3d2013-01-17 01:17:56 +00005443 /// \brief Find the object which is produced by the specified expression,
5444 /// if any.
5445 Object getObject(Expr *E, bool Mod) const {
5446 E = E->IgnoreParenCasts();
5447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5448 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5449 return getObject(UO->getSubExpr(), Mod);
5450 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5451 if (BO->getOpcode() == BO_Comma)
5452 return getObject(BO->getRHS(), Mod);
5453 if (Mod && BO->isAssignmentOp())
5454 return getObject(BO->getLHS(), Mod);
5455 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5456 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5457 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5458 return ME->getMemberDecl();
5459 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5460 // FIXME: If this is a reference, map through to its value.
5461 return DRE->getDecl();
5462 return 0;
5463 }
5464
5465 /// \brief Note that an object was modified or used by an expression.
5466 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5467 Usage &U = UI.Uses[UK];
5468 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5469 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5470 ModAsSideEffect->push_back(std::make_pair(O, U));
5471 U.Use = Ref;
5472 U.Seq = Region;
5473 }
5474 }
5475 /// \brief Check whether a modification or use conflicts with a prior usage.
5476 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5477 bool IsModMod) {
5478 if (UI.Diagnosed)
5479 return;
5480
5481 const Usage &U = UI.Uses[OtherKind];
5482 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5483 return;
5484
5485 Expr *Mod = U.Use;
5486 Expr *ModOrUse = Ref;
5487 if (OtherKind == UK_Use)
5488 std::swap(Mod, ModOrUse);
5489
5490 SemaRef.Diag(Mod->getExprLoc(),
5491 IsModMod ? diag::warn_unsequenced_mod_mod
5492 : diag::warn_unsequenced_mod_use)
5493 << O << SourceRange(ModOrUse->getExprLoc());
5494 UI.Diagnosed = true;
5495 }
5496
5497 void notePreUse(Object O, Expr *Use) {
5498 UsageInfo &U = UsageMap[O];
5499 // Uses conflict with other modifications.
5500 checkUsage(O, U, Use, UK_ModAsValue, false);
5501 }
5502 void notePostUse(Object O, Expr *Use) {
5503 UsageInfo &U = UsageMap[O];
5504 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5505 addUsage(U, O, Use, UK_Use);
5506 }
5507
5508 void notePreMod(Object O, Expr *Mod) {
5509 UsageInfo &U = UsageMap[O];
5510 // Modifications conflict with other modifications and with uses.
5511 checkUsage(O, U, Mod, UK_ModAsValue, true);
5512 checkUsage(O, U, Mod, UK_Use, false);
5513 }
5514 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5515 UsageInfo &U = UsageMap[O];
5516 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5517 addUsage(U, O, Use, UK);
5518 }
5519
5520public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005521 SequenceChecker(Sema &S, Expr *E,
5522 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005523 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5524 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005525 Visit(E);
5526 }
5527
5528 void VisitStmt(Stmt *S) {
5529 // Skip all statements which aren't expressions for now.
5530 }
5531
5532 void VisitExpr(Expr *E) {
5533 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005534 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005535 }
5536
5537 void VisitCastExpr(CastExpr *E) {
5538 Object O = Object();
5539 if (E->getCastKind() == CK_LValueToRValue)
5540 O = getObject(E->getSubExpr(), false);
5541
5542 if (O)
5543 notePreUse(O, E);
5544 VisitExpr(E);
5545 if (O)
5546 notePostUse(O, E);
5547 }
5548
5549 void VisitBinComma(BinaryOperator *BO) {
5550 // C++11 [expr.comma]p1:
5551 // Every value computation and side effect associated with the left
5552 // expression is sequenced before every value computation and side
5553 // effect associated with the right expression.
5554 SequenceTree::Seq LHS = Tree.allocate(Region);
5555 SequenceTree::Seq RHS = Tree.allocate(Region);
5556 SequenceTree::Seq OldRegion = Region;
5557
5558 {
5559 SequencedSubexpression SeqLHS(*this);
5560 Region = LHS;
5561 Visit(BO->getLHS());
5562 }
5563
5564 Region = RHS;
5565 Visit(BO->getRHS());
5566
5567 Region = OldRegion;
5568
5569 // Forget that LHS and RHS are sequenced. They are both unsequenced
5570 // with respect to other stuff.
5571 Tree.merge(LHS);
5572 Tree.merge(RHS);
5573 }
5574
5575 void VisitBinAssign(BinaryOperator *BO) {
5576 // The modification is sequenced after the value computation of the LHS
5577 // and RHS, so check it before inspecting the operands and update the
5578 // map afterwards.
5579 Object O = getObject(BO->getLHS(), true);
5580 if (!O)
5581 return VisitExpr(BO);
5582
5583 notePreMod(O, BO);
5584
5585 // C++11 [expr.ass]p7:
5586 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5587 // only once.
5588 //
5589 // Therefore, for a compound assignment operator, O is considered used
5590 // everywhere except within the evaluation of E1 itself.
5591 if (isa<CompoundAssignOperator>(BO))
5592 notePreUse(O, BO);
5593
5594 Visit(BO->getLHS());
5595
5596 if (isa<CompoundAssignOperator>(BO))
5597 notePostUse(O, BO);
5598
5599 Visit(BO->getRHS());
5600
Richard Smith418dd3e2013-06-26 23:16:51 +00005601 // C++11 [expr.ass]p1:
5602 // the assignment is sequenced [...] before the value computation of the
5603 // assignment expression.
5604 // C11 6.5.16/3 has no such rule.
5605 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5606 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005607 }
5608 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5609 VisitBinAssign(CAO);
5610 }
5611
5612 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5613 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5614 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5615 Object O = getObject(UO->getSubExpr(), true);
5616 if (!O)
5617 return VisitExpr(UO);
5618
5619 notePreMod(O, UO);
5620 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005621 // C++11 [expr.pre.incr]p1:
5622 // the expression ++x is equivalent to x+=1
5623 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5624 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005625 }
5626
5627 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5628 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5629 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5630 Object O = getObject(UO->getSubExpr(), true);
5631 if (!O)
5632 return VisitExpr(UO);
5633
5634 notePreMod(O, UO);
5635 Visit(UO->getSubExpr());
5636 notePostMod(O, UO, UK_ModAsSideEffect);
5637 }
5638
5639 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5640 void VisitBinLOr(BinaryOperator *BO) {
5641 // The side-effects of the LHS of an '&&' are sequenced before the
5642 // value computation of the RHS, and hence before the value computation
5643 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5644 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005645 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005646 {
5647 SequencedSubexpression Sequenced(*this);
5648 Visit(BO->getLHS());
5649 }
5650
5651 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005652 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005653 if (!Result)
5654 Visit(BO->getRHS());
5655 } else {
5656 // Check for unsequenced operations in the RHS, treating it as an
5657 // entirely separate evaluation.
5658 //
5659 // FIXME: If there are operations in the RHS which are unsequenced
5660 // with respect to operations outside the RHS, and those operations
5661 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005662 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005663 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005664 }
5665 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005666 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005667 {
5668 SequencedSubexpression Sequenced(*this);
5669 Visit(BO->getLHS());
5670 }
5671
5672 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005673 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005674 if (Result)
5675 Visit(BO->getRHS());
5676 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005677 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005678 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005679 }
5680
5681 // Only visit the condition, unless we can be sure which subexpression will
5682 // be chosen.
5683 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005684 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005685 {
5686 SequencedSubexpression Sequenced(*this);
5687 Visit(CO->getCond());
5688 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005689
5690 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005691 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005692 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005693 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005694 WorkList.push_back(CO->getTrueExpr());
5695 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005696 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005697 }
5698
Richard Smith0c0b3902013-06-30 10:40:20 +00005699 void VisitCallExpr(CallExpr *CE) {
5700 // C++11 [intro.execution]p15:
5701 // When calling a function [...], every value computation and side effect
5702 // associated with any argument expression, or with the postfix expression
5703 // designating the called function, is sequenced before execution of every
5704 // expression or statement in the body of the function [and thus before
5705 // the value computation of its result].
5706 SequencedSubexpression Sequenced(*this);
5707 Base::VisitCallExpr(CE);
5708
5709 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5710 }
5711
Richard Smith6c3af3d2013-01-17 01:17:56 +00005712 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005713 // This is a call, so all subexpressions are sequenced before the result.
5714 SequencedSubexpression Sequenced(*this);
5715
Richard Smith6c3af3d2013-01-17 01:17:56 +00005716 if (!CCE->isListInitialization())
5717 return VisitExpr(CCE);
5718
5719 // In C++11, list initializations are sequenced.
5720 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5721 SequenceTree::Seq Parent = Region;
5722 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5723 E = CCE->arg_end();
5724 I != E; ++I) {
5725 Region = Tree.allocate(Parent);
5726 Elts.push_back(Region);
5727 Visit(*I);
5728 }
5729
5730 // Forget that the initializers are sequenced.
5731 Region = Parent;
5732 for (unsigned I = 0; I < Elts.size(); ++I)
5733 Tree.merge(Elts[I]);
5734 }
5735
5736 void VisitInitListExpr(InitListExpr *ILE) {
5737 if (!SemaRef.getLangOpts().CPlusPlus11)
5738 return VisitExpr(ILE);
5739
5740 // In C++11, list initializations are sequenced.
5741 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5742 SequenceTree::Seq Parent = Region;
5743 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5744 Expr *E = ILE->getInit(I);
5745 if (!E) continue;
5746 Region = Tree.allocate(Parent);
5747 Elts.push_back(Region);
5748 Visit(E);
5749 }
5750
5751 // Forget that the initializers are sequenced.
5752 Region = Parent;
5753 for (unsigned I = 0; I < Elts.size(); ++I)
5754 Tree.merge(Elts[I]);
5755 }
5756};
5757}
5758
5759void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005760 llvm::SmallVector<Expr*, 8> WorkList;
5761 WorkList.push_back(E);
5762 while (!WorkList.empty()) {
5763 Expr *Item = WorkList.back();
5764 WorkList.pop_back();
5765 SequenceChecker(*this, Item, WorkList);
5766 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005767}
5768
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005769void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5770 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005771 CheckImplicitConversions(E, CheckLoc);
5772 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005773 if (!IsConstexpr && !E->isValueDependent())
5774 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005775}
5776
John McCall15d7d122010-11-11 03:21:53 +00005777void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5778 FieldDecl *BitField,
5779 Expr *Init) {
5780 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5781}
5782
Mike Stumpf8c49212010-01-21 03:59:47 +00005783/// CheckParmsForFunctionDef - Check that the parameters of the given
5784/// function are appropriate for the definition of a function. This
5785/// takes care of any checks that cannot be performed on the
5786/// declaration itself, e.g., that the types of each of the function
5787/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00005788bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
5789 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00005790 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005791 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005792 for (; P != PEnd; ++P) {
5793 ParmVarDecl *Param = *P;
5794
Mike Stumpf8c49212010-01-21 03:59:47 +00005795 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5796 // function declarator that is part of a function definition of
5797 // that function shall not have incomplete type.
5798 //
5799 // This is also C++ [dcl.fct]p6.
5800 if (!Param->isInvalidDecl() &&
5801 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005802 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005803 Param->setInvalidDecl();
5804 HasInvalidParm = true;
5805 }
5806
5807 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5808 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005809 if (CheckParameterNames &&
5810 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005811 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005812 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005813 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005814
5815 // C99 6.7.5.3p12:
5816 // If the function declarator is not part of a definition of that
5817 // function, parameters may have incomplete type and may use the [*]
5818 // notation in their sequences of declarator specifiers to specify
5819 // variable length array types.
5820 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005821 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005822 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005823 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005824 // information is added for it.
5825 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005826 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005827 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005828 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005829 }
Reid Kleckner9b601952013-06-21 12:45:15 +00005830
5831 // MSVC destroys objects passed by value in the callee. Therefore a
5832 // function definition which takes such a parameter must be able to call the
5833 // object's destructor.
5834 if (getLangOpts().CPlusPlus &&
5835 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
5836 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
5837 FinalizeVarWithDestructor(Param, RT);
5838 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005839 }
5840
5841 return HasInvalidParm;
5842}
John McCallb7f4ffe2010-08-12 21:44:57 +00005843
5844/// CheckCastAlign - Implements -Wcast-align, which warns when a
5845/// pointer cast increases the alignment requirements.
5846void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5847 // This is actually a lot of work to potentially be doing on every
5848 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005849 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5850 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005851 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005852 return;
5853
5854 // Ignore dependent types.
5855 if (T->isDependentType() || Op->getType()->isDependentType())
5856 return;
5857
5858 // Require that the destination be a pointer type.
5859 const PointerType *DestPtr = T->getAs<PointerType>();
5860 if (!DestPtr) return;
5861
5862 // If the destination has alignment 1, we're done.
5863 QualType DestPointee = DestPtr->getPointeeType();
5864 if (DestPointee->isIncompleteType()) return;
5865 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5866 if (DestAlign.isOne()) return;
5867
5868 // Require that the source be a pointer type.
5869 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5870 if (!SrcPtr) return;
5871 QualType SrcPointee = SrcPtr->getPointeeType();
5872
5873 // Whitelist casts from cv void*. We already implicitly
5874 // whitelisted casts to cv void*, since they have alignment 1.
5875 // Also whitelist casts involving incomplete types, which implicitly
5876 // includes 'void'.
5877 if (SrcPointee->isIncompleteType()) return;
5878
5879 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5880 if (SrcAlign >= DestAlign) return;
5881
5882 Diag(TRange.getBegin(), diag::warn_cast_align)
5883 << Op->getType() << T
5884 << static_cast<unsigned>(SrcAlign.getQuantity())
5885 << static_cast<unsigned>(DestAlign.getQuantity())
5886 << TRange << Op->getSourceRange();
5887}
5888
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005889static const Type* getElementType(const Expr *BaseExpr) {
5890 const Type* EltType = BaseExpr->getType().getTypePtr();
5891 if (EltType->isAnyPointerType())
5892 return EltType->getPointeeType().getTypePtr();
5893 else if (EltType->isArrayType())
5894 return EltType->getBaseElementTypeUnsafe();
5895 return EltType;
5896}
5897
Chandler Carruthc2684342011-08-05 09:10:50 +00005898/// \brief Check whether this array fits the idiom of a size-one tail padded
5899/// array member of a struct.
5900///
5901/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5902/// commonly used to emulate flexible arrays in C89 code.
5903static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5904 const NamedDecl *ND) {
5905 if (Size != 1 || !ND) return false;
5906
5907 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5908 if (!FD) return false;
5909
5910 // Don't consider sizes resulting from macro expansions or template argument
5911 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005912
5913 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005914 while (TInfo) {
5915 TypeLoc TL = TInfo->getTypeLoc();
5916 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005917 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5918 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005919 TInfo = TDL->getTypeSourceInfo();
5920 continue;
5921 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005922 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5923 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005924 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5925 return false;
5926 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005927 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005928 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005929
5930 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005931 if (!RD) return false;
5932 if (RD->isUnion()) return false;
5933 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5934 if (!CRD->isStandardLayout()) return false;
5935 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005936
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005937 // See if this is the last field decl in the record.
5938 const Decl *D = FD;
5939 while ((D = D->getNextDeclInContext()))
5940 if (isa<FieldDecl>(D))
5941 return false;
5942 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005943}
5944
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005945void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005946 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005947 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005948 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005949 if (IndexExpr->isValueDependent())
5950 return;
5951
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005952 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005953 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005954 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005955 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005956 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005957 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005958
Chandler Carruth34064582011-02-17 20:55:08 +00005959 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005960 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005961 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005962 if (IndexNegated)
5963 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005964
Chandler Carruthba447122011-08-05 08:07:29 +00005965 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005966 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5967 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005968 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005969 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005970
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005971 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005972 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005973 if (!size.isStrictlyPositive())
5974 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005975
5976 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005977 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005978 // Make sure we're comparing apples to apples when comparing index to size
5979 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5980 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005981 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005982 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005983 if (ptrarith_typesize != array_typesize) {
5984 // There's a cast to a different size type involved
5985 uint64_t ratio = array_typesize / ptrarith_typesize;
5986 // TODO: Be smarter about handling cases where array_typesize is not a
5987 // multiple of ptrarith_typesize
5988 if (ptrarith_typesize * ratio == array_typesize)
5989 size *= llvm::APInt(size.getBitWidth(), ratio);
5990 }
5991 }
5992
Chandler Carruth34064582011-02-17 20:55:08 +00005993 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005994 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005995 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005996 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005997
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005998 // For array subscripting the index must be less than size, but for pointer
5999 // arithmetic also allow the index (offset) to be equal to size since
6000 // computing the next address after the end of the array is legal and
6001 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006002 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006003 return;
6004
6005 // Also don't warn for arrays of size 1 which are members of some
6006 // structure. These are often used to approximate flexible arrays in C89
6007 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006008 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006009 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006010
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006011 // Suppress the warning if the subscript expression (as identified by the
6012 // ']' location) and the index expression are both from macro expansions
6013 // within a system header.
6014 if (ASE) {
6015 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6016 ASE->getRBracketLoc());
6017 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6018 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6019 IndexExpr->getLocStart());
6020 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6021 return;
6022 }
6023 }
6024
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006025 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006026 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006027 DiagID = diag::warn_array_index_exceeds_bounds;
6028
6029 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6030 PDiag(DiagID) << index.toString(10, true)
6031 << size.toString(10, true)
6032 << (unsigned)size.getLimitedValue(~0U)
6033 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006034 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006035 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006036 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006037 DiagID = diag::warn_ptr_arith_precedes_bounds;
6038 if (index.isNegative()) index = -index;
6039 }
6040
6041 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6042 PDiag(DiagID) << index.toString(10, true)
6043 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006044 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006045
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006046 if (!ND) {
6047 // Try harder to find a NamedDecl to point at in the note.
6048 while (const ArraySubscriptExpr *ASE =
6049 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6050 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6051 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6052 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6053 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6054 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6055 }
6056
Chandler Carruth35001ca2011-02-17 21:10:52 +00006057 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006058 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6059 PDiag(diag::note_array_index_out_of_bounds)
6060 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006061}
6062
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006063void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006064 int AllowOnePastEnd = 0;
6065 while (expr) {
6066 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006067 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006068 case Stmt::ArraySubscriptExprClass: {
6069 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006070 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006071 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006072 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006073 }
6074 case Stmt::UnaryOperatorClass: {
6075 // Only unwrap the * and & unary operators
6076 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6077 expr = UO->getSubExpr();
6078 switch (UO->getOpcode()) {
6079 case UO_AddrOf:
6080 AllowOnePastEnd++;
6081 break;
6082 case UO_Deref:
6083 AllowOnePastEnd--;
6084 break;
6085 default:
6086 return;
6087 }
6088 break;
6089 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006090 case Stmt::ConditionalOperatorClass: {
6091 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6092 if (const Expr *lhs = cond->getLHS())
6093 CheckArrayAccess(lhs);
6094 if (const Expr *rhs = cond->getRHS())
6095 CheckArrayAccess(rhs);
6096 return;
6097 }
6098 default:
6099 return;
6100 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006101 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006102}
John McCallf85e1932011-06-15 23:02:42 +00006103
6104//===--- CHECK: Objective-C retain cycles ----------------------------------//
6105
6106namespace {
6107 struct RetainCycleOwner {
6108 RetainCycleOwner() : Variable(0), Indirect(false) {}
6109 VarDecl *Variable;
6110 SourceRange Range;
6111 SourceLocation Loc;
6112 bool Indirect;
6113
6114 void setLocsFrom(Expr *e) {
6115 Loc = e->getExprLoc();
6116 Range = e->getSourceRange();
6117 }
6118 };
6119}
6120
6121/// Consider whether capturing the given variable can possibly lead to
6122/// a retain cycle.
6123static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006124 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006125 // lifetime. In MRR, it's captured strongly if the variable is
6126 // __block and has an appropriate type.
6127 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6128 return false;
6129
6130 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006131 if (ref)
6132 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006133 return true;
6134}
6135
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006136static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006137 while (true) {
6138 e = e->IgnoreParens();
6139 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6140 switch (cast->getCastKind()) {
6141 case CK_BitCast:
6142 case CK_LValueBitCast:
6143 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006144 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006145 e = cast->getSubExpr();
6146 continue;
6147
John McCallf85e1932011-06-15 23:02:42 +00006148 default:
6149 return false;
6150 }
6151 }
6152
6153 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6154 ObjCIvarDecl *ivar = ref->getDecl();
6155 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6156 return false;
6157
6158 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006159 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006160 return false;
6161
6162 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6163 owner.Indirect = true;
6164 return true;
6165 }
6166
6167 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6168 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6169 if (!var) return false;
6170 return considerVariable(var, ref, owner);
6171 }
6172
John McCallf85e1932011-06-15 23:02:42 +00006173 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6174 if (member->isArrow()) return false;
6175
6176 // Don't count this as an indirect ownership.
6177 e = member->getBase();
6178 continue;
6179 }
6180
John McCall4b9c2d22011-11-06 09:01:30 +00006181 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6182 // Only pay attention to pseudo-objects on property references.
6183 ObjCPropertyRefExpr *pre
6184 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6185 ->IgnoreParens());
6186 if (!pre) return false;
6187 if (pre->isImplicitProperty()) return false;
6188 ObjCPropertyDecl *property = pre->getExplicitProperty();
6189 if (!property->isRetaining() &&
6190 !(property->getPropertyIvarDecl() &&
6191 property->getPropertyIvarDecl()->getType()
6192 .getObjCLifetime() == Qualifiers::OCL_Strong))
6193 return false;
6194
6195 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006196 if (pre->isSuperReceiver()) {
6197 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6198 if (!owner.Variable)
6199 return false;
6200 owner.Loc = pre->getLocation();
6201 owner.Range = pre->getSourceRange();
6202 return true;
6203 }
John McCall4b9c2d22011-11-06 09:01:30 +00006204 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6205 ->getSourceExpr());
6206 continue;
6207 }
6208
John McCallf85e1932011-06-15 23:02:42 +00006209 // Array ivars?
6210
6211 return false;
6212 }
6213}
6214
6215namespace {
6216 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6217 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6218 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6219 Variable(variable), Capturer(0) {}
6220
6221 VarDecl *Variable;
6222 Expr *Capturer;
6223
6224 void VisitDeclRefExpr(DeclRefExpr *ref) {
6225 if (ref->getDecl() == Variable && !Capturer)
6226 Capturer = ref;
6227 }
6228
John McCallf85e1932011-06-15 23:02:42 +00006229 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6230 if (Capturer) return;
6231 Visit(ref->getBase());
6232 if (Capturer && ref->isFreeIvar())
6233 Capturer = ref;
6234 }
6235
6236 void VisitBlockExpr(BlockExpr *block) {
6237 // Look inside nested blocks
6238 if (block->getBlockDecl()->capturesVariable(Variable))
6239 Visit(block->getBlockDecl()->getBody());
6240 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006241
6242 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6243 if (Capturer) return;
6244 if (OVE->getSourceExpr())
6245 Visit(OVE->getSourceExpr());
6246 }
John McCallf85e1932011-06-15 23:02:42 +00006247 };
6248}
6249
6250/// Check whether the given argument is a block which captures a
6251/// variable.
6252static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6253 assert(owner.Variable && owner.Loc.isValid());
6254
6255 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006256
6257 // Look through [^{...} copy] and Block_copy(^{...}).
6258 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6259 Selector Cmd = ME->getSelector();
6260 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6261 e = ME->getInstanceReceiver();
6262 if (!e)
6263 return 0;
6264 e = e->IgnoreParenCasts();
6265 }
6266 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6267 if (CE->getNumArgs() == 1) {
6268 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006269 if (Fn) {
6270 const IdentifierInfo *FnI = Fn->getIdentifier();
6271 if (FnI && FnI->isStr("_Block_copy")) {
6272 e = CE->getArg(0)->IgnoreParenCasts();
6273 }
6274 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006275 }
6276 }
6277
John McCallf85e1932011-06-15 23:02:42 +00006278 BlockExpr *block = dyn_cast<BlockExpr>(e);
6279 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6280 return 0;
6281
6282 FindCaptureVisitor visitor(S.Context, owner.Variable);
6283 visitor.Visit(block->getBlockDecl()->getBody());
6284 return visitor.Capturer;
6285}
6286
6287static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6288 RetainCycleOwner &owner) {
6289 assert(capturer);
6290 assert(owner.Variable && owner.Loc.isValid());
6291
6292 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6293 << owner.Variable << capturer->getSourceRange();
6294 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6295 << owner.Indirect << owner.Range;
6296}
6297
6298/// Check for a keyword selector that starts with the word 'add' or
6299/// 'set'.
6300static bool isSetterLikeSelector(Selector sel) {
6301 if (sel.isUnarySelector()) return false;
6302
Chris Lattner5f9e2722011-07-23 10:55:15 +00006303 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006304 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006305 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006306 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006307 else if (str.startswith("add")) {
6308 // Specially whitelist 'addOperationWithBlock:'.
6309 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6310 return false;
6311 str = str.substr(3);
6312 }
John McCallf85e1932011-06-15 23:02:42 +00006313 else
6314 return false;
6315
6316 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006317 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006318}
6319
6320/// Check a message send to see if it's likely to cause a retain cycle.
6321void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6322 // Only check instance methods whose selector looks like a setter.
6323 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6324 return;
6325
6326 // Try to find a variable that the receiver is strongly owned by.
6327 RetainCycleOwner owner;
6328 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006329 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006330 return;
6331 } else {
6332 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6333 owner.Variable = getCurMethodDecl()->getSelfDecl();
6334 owner.Loc = msg->getSuperLoc();
6335 owner.Range = msg->getSuperLoc();
6336 }
6337
6338 // Check whether the receiver is captured by any of the arguments.
6339 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6340 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6341 return diagnoseRetainCycle(*this, capturer, owner);
6342}
6343
6344/// Check a property assign to see if it's likely to cause a retain cycle.
6345void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6346 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006347 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006348 return;
6349
6350 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6351 diagnoseRetainCycle(*this, capturer, owner);
6352}
6353
Jordan Rosee10f4d32012-09-15 02:48:31 +00006354void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6355 RetainCycleOwner Owner;
6356 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6357 return;
6358
6359 // Because we don't have an expression for the variable, we have to set the
6360 // location explicitly here.
6361 Owner.Loc = Var->getLocation();
6362 Owner.Range = Var->getSourceRange();
6363
6364 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6365 diagnoseRetainCycle(*this, Capturer, Owner);
6366}
6367
Ted Kremenek9d084012012-12-21 08:04:28 +00006368static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6369 Expr *RHS, bool isProperty) {
6370 // Check if RHS is an Objective-C object literal, which also can get
6371 // immediately zapped in a weak reference. Note that we explicitly
6372 // allow ObjCStringLiterals, since those are designed to never really die.
6373 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006374
Ted Kremenekd3292c82012-12-21 22:46:35 +00006375 // This enum needs to match with the 'select' in
6376 // warn_objc_arc_literal_assign (off-by-1).
6377 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6378 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6379 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006380
6381 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006382 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006383 << (isProperty ? 0 : 1)
6384 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006385
6386 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006387}
6388
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006389static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6390 Qualifiers::ObjCLifetime LT,
6391 Expr *RHS, bool isProperty) {
6392 // Strip off any implicit cast added to get to the one ARC-specific.
6393 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6394 if (cast->getCastKind() == CK_ARCConsumeObject) {
6395 S.Diag(Loc, diag::warn_arc_retained_assign)
6396 << (LT == Qualifiers::OCL_ExplicitNone)
6397 << (isProperty ? 0 : 1)
6398 << RHS->getSourceRange();
6399 return true;
6400 }
6401 RHS = cast->getSubExpr();
6402 }
6403
6404 if (LT == Qualifiers::OCL_Weak &&
6405 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6406 return true;
6407
6408 return false;
6409}
6410
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006411bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6412 QualType LHS, Expr *RHS) {
6413 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6414
6415 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6416 return false;
6417
6418 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6419 return true;
6420
6421 return false;
6422}
6423
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006424void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6425 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006426 QualType LHSType;
6427 // PropertyRef on LHS type need be directly obtained from
6428 // its declaration as it has a PsuedoType.
6429 ObjCPropertyRefExpr *PRE
6430 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6431 if (PRE && !PRE->isImplicitProperty()) {
6432 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6433 if (PD)
6434 LHSType = PD->getType();
6435 }
6436
6437 if (LHSType.isNull())
6438 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006439
6440 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6441
6442 if (LT == Qualifiers::OCL_Weak) {
6443 DiagnosticsEngine::Level Level =
6444 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6445 if (Level != DiagnosticsEngine::Ignored)
6446 getCurFunction()->markSafeWeakUse(LHS);
6447 }
6448
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006449 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6450 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006451
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006452 // FIXME. Check for other life times.
6453 if (LT != Qualifiers::OCL_None)
6454 return;
6455
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006456 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006457 if (PRE->isImplicitProperty())
6458 return;
6459 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6460 if (!PD)
6461 return;
6462
Bill Wendlingad017fa2012-12-20 19:22:21 +00006463 unsigned Attributes = PD->getPropertyAttributes();
6464 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006465 // when 'assign' attribute was not explicitly specified
6466 // by user, ignore it and rely on property type itself
6467 // for lifetime info.
6468 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6469 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6470 LHSType->isObjCRetainableType())
6471 return;
6472
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006473 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006474 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006475 Diag(Loc, diag::warn_arc_retained_property_assign)
6476 << RHS->getSourceRange();
6477 return;
6478 }
6479 RHS = cast->getSubExpr();
6480 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006481 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006482 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006483 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6484 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006485 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006486 }
6487}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006488
6489//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6490
6491namespace {
6492bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6493 SourceLocation StmtLoc,
6494 const NullStmt *Body) {
6495 // Do not warn if the body is a macro that expands to nothing, e.g:
6496 //
6497 // #define CALL(x)
6498 // if (condition)
6499 // CALL(0);
6500 //
6501 if (Body->hasLeadingEmptyMacro())
6502 return false;
6503
6504 // Get line numbers of statement and body.
6505 bool StmtLineInvalid;
6506 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6507 &StmtLineInvalid);
6508 if (StmtLineInvalid)
6509 return false;
6510
6511 bool BodyLineInvalid;
6512 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6513 &BodyLineInvalid);
6514 if (BodyLineInvalid)
6515 return false;
6516
6517 // Warn if null statement and body are on the same line.
6518 if (StmtLine != BodyLine)
6519 return false;
6520
6521 return true;
6522}
6523} // Unnamed namespace
6524
6525void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6526 const Stmt *Body,
6527 unsigned DiagID) {
6528 // Since this is a syntactic check, don't emit diagnostic for template
6529 // instantiations, this just adds noise.
6530 if (CurrentInstantiationScope)
6531 return;
6532
6533 // The body should be a null statement.
6534 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6535 if (!NBody)
6536 return;
6537
6538 // Do the usual checks.
6539 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6540 return;
6541
6542 Diag(NBody->getSemiLoc(), DiagID);
6543 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6544}
6545
6546void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6547 const Stmt *PossibleBody) {
6548 assert(!CurrentInstantiationScope); // Ensured by caller
6549
6550 SourceLocation StmtLoc;
6551 const Stmt *Body;
6552 unsigned DiagID;
6553 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6554 StmtLoc = FS->getRParenLoc();
6555 Body = FS->getBody();
6556 DiagID = diag::warn_empty_for_body;
6557 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6558 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6559 Body = WS->getBody();
6560 DiagID = diag::warn_empty_while_body;
6561 } else
6562 return; // Neither `for' nor `while'.
6563
6564 // The body should be a null statement.
6565 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6566 if (!NBody)
6567 return;
6568
6569 // Skip expensive checks if diagnostic is disabled.
6570 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6571 DiagnosticsEngine::Ignored)
6572 return;
6573
6574 // Do the usual checks.
6575 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6576 return;
6577
6578 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6579 // noise level low, emit diagnostics only if for/while is followed by a
6580 // CompoundStmt, e.g.:
6581 // for (int i = 0; i < n; i++);
6582 // {
6583 // a(i);
6584 // }
6585 // or if for/while is followed by a statement with more indentation
6586 // than for/while itself:
6587 // for (int i = 0; i < n; i++);
6588 // a(i);
6589 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6590 if (!ProbableTypo) {
6591 bool BodyColInvalid;
6592 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6593 PossibleBody->getLocStart(),
6594 &BodyColInvalid);
6595 if (BodyColInvalid)
6596 return;
6597
6598 bool StmtColInvalid;
6599 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6600 S->getLocStart(),
6601 &StmtColInvalid);
6602 if (StmtColInvalid)
6603 return;
6604
6605 if (BodyCol > StmtCol)
6606 ProbableTypo = true;
6607 }
6608
6609 if (ProbableTypo) {
6610 Diag(NBody->getSemiLoc(), DiagID);
6611 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6612 }
6613}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006614
6615//===--- Layout compatibility ----------------------------------------------//
6616
6617namespace {
6618
6619bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6620
6621/// \brief Check if two enumeration types are layout-compatible.
6622bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6623 // C++11 [dcl.enum] p8:
6624 // Two enumeration types are layout-compatible if they have the same
6625 // underlying type.
6626 return ED1->isComplete() && ED2->isComplete() &&
6627 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6628}
6629
6630/// \brief Check if two fields are layout-compatible.
6631bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6632 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6633 return false;
6634
6635 if (Field1->isBitField() != Field2->isBitField())
6636 return false;
6637
6638 if (Field1->isBitField()) {
6639 // Make sure that the bit-fields are the same length.
6640 unsigned Bits1 = Field1->getBitWidthValue(C);
6641 unsigned Bits2 = Field2->getBitWidthValue(C);
6642
6643 if (Bits1 != Bits2)
6644 return false;
6645 }
6646
6647 return true;
6648}
6649
6650/// \brief Check if two standard-layout structs are layout-compatible.
6651/// (C++11 [class.mem] p17)
6652bool isLayoutCompatibleStruct(ASTContext &C,
6653 RecordDecl *RD1,
6654 RecordDecl *RD2) {
6655 // If both records are C++ classes, check that base classes match.
6656 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6657 // If one of records is a CXXRecordDecl we are in C++ mode,
6658 // thus the other one is a CXXRecordDecl, too.
6659 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6660 // Check number of base classes.
6661 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6662 return false;
6663
6664 // Check the base classes.
6665 for (CXXRecordDecl::base_class_const_iterator
6666 Base1 = D1CXX->bases_begin(),
6667 BaseEnd1 = D1CXX->bases_end(),
6668 Base2 = D2CXX->bases_begin();
6669 Base1 != BaseEnd1;
6670 ++Base1, ++Base2) {
6671 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6672 return false;
6673 }
6674 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6675 // If only RD2 is a C++ class, it should have zero base classes.
6676 if (D2CXX->getNumBases() > 0)
6677 return false;
6678 }
6679
6680 // Check the fields.
6681 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6682 Field2End = RD2->field_end(),
6683 Field1 = RD1->field_begin(),
6684 Field1End = RD1->field_end();
6685 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6686 if (!isLayoutCompatible(C, *Field1, *Field2))
6687 return false;
6688 }
6689 if (Field1 != Field1End || Field2 != Field2End)
6690 return false;
6691
6692 return true;
6693}
6694
6695/// \brief Check if two standard-layout unions are layout-compatible.
6696/// (C++11 [class.mem] p18)
6697bool isLayoutCompatibleUnion(ASTContext &C,
6698 RecordDecl *RD1,
6699 RecordDecl *RD2) {
6700 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6701 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6702 Field2End = RD2->field_end();
6703 Field2 != Field2End; ++Field2) {
6704 UnmatchedFields.insert(*Field2);
6705 }
6706
6707 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6708 Field1End = RD1->field_end();
6709 Field1 != Field1End; ++Field1) {
6710 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6711 I = UnmatchedFields.begin(),
6712 E = UnmatchedFields.end();
6713
6714 for ( ; I != E; ++I) {
6715 if (isLayoutCompatible(C, *Field1, *I)) {
6716 bool Result = UnmatchedFields.erase(*I);
6717 (void) Result;
6718 assert(Result);
6719 break;
6720 }
6721 }
6722 if (I == E)
6723 return false;
6724 }
6725
6726 return UnmatchedFields.empty();
6727}
6728
6729bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6730 if (RD1->isUnion() != RD2->isUnion())
6731 return false;
6732
6733 if (RD1->isUnion())
6734 return isLayoutCompatibleUnion(C, RD1, RD2);
6735 else
6736 return isLayoutCompatibleStruct(C, RD1, RD2);
6737}
6738
6739/// \brief Check if two types are layout-compatible in C++11 sense.
6740bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6741 if (T1.isNull() || T2.isNull())
6742 return false;
6743
6744 // C++11 [basic.types] p11:
6745 // If two types T1 and T2 are the same type, then T1 and T2 are
6746 // layout-compatible types.
6747 if (C.hasSameType(T1, T2))
6748 return true;
6749
6750 T1 = T1.getCanonicalType().getUnqualifiedType();
6751 T2 = T2.getCanonicalType().getUnqualifiedType();
6752
6753 const Type::TypeClass TC1 = T1->getTypeClass();
6754 const Type::TypeClass TC2 = T2->getTypeClass();
6755
6756 if (TC1 != TC2)
6757 return false;
6758
6759 if (TC1 == Type::Enum) {
6760 return isLayoutCompatible(C,
6761 cast<EnumType>(T1)->getDecl(),
6762 cast<EnumType>(T2)->getDecl());
6763 } else if (TC1 == Type::Record) {
6764 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6765 return false;
6766
6767 return isLayoutCompatible(C,
6768 cast<RecordType>(T1)->getDecl(),
6769 cast<RecordType>(T2)->getDecl());
6770 }
6771
6772 return false;
6773}
6774}
6775
6776//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6777
6778namespace {
6779/// \brief Given a type tag expression find the type tag itself.
6780///
6781/// \param TypeExpr Type tag expression, as it appears in user's code.
6782///
6783/// \param VD Declaration of an identifier that appears in a type tag.
6784///
6785/// \param MagicValue Type tag magic value.
6786bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6787 const ValueDecl **VD, uint64_t *MagicValue) {
6788 while(true) {
6789 if (!TypeExpr)
6790 return false;
6791
6792 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6793
6794 switch (TypeExpr->getStmtClass()) {
6795 case Stmt::UnaryOperatorClass: {
6796 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6797 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6798 TypeExpr = UO->getSubExpr();
6799 continue;
6800 }
6801 return false;
6802 }
6803
6804 case Stmt::DeclRefExprClass: {
6805 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6806 *VD = DRE->getDecl();
6807 return true;
6808 }
6809
6810 case Stmt::IntegerLiteralClass: {
6811 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6812 llvm::APInt MagicValueAPInt = IL->getValue();
6813 if (MagicValueAPInt.getActiveBits() <= 64) {
6814 *MagicValue = MagicValueAPInt.getZExtValue();
6815 return true;
6816 } else
6817 return false;
6818 }
6819
6820 case Stmt::BinaryConditionalOperatorClass:
6821 case Stmt::ConditionalOperatorClass: {
6822 const AbstractConditionalOperator *ACO =
6823 cast<AbstractConditionalOperator>(TypeExpr);
6824 bool Result;
6825 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6826 if (Result)
6827 TypeExpr = ACO->getTrueExpr();
6828 else
6829 TypeExpr = ACO->getFalseExpr();
6830 continue;
6831 }
6832 return false;
6833 }
6834
6835 case Stmt::BinaryOperatorClass: {
6836 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6837 if (BO->getOpcode() == BO_Comma) {
6838 TypeExpr = BO->getRHS();
6839 continue;
6840 }
6841 return false;
6842 }
6843
6844 default:
6845 return false;
6846 }
6847 }
6848}
6849
6850/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6851///
6852/// \param TypeExpr Expression that specifies a type tag.
6853///
6854/// \param MagicValues Registered magic values.
6855///
6856/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6857/// kind.
6858///
6859/// \param TypeInfo Information about the corresponding C type.
6860///
6861/// \returns true if the corresponding C type was found.
6862bool GetMatchingCType(
6863 const IdentifierInfo *ArgumentKind,
6864 const Expr *TypeExpr, const ASTContext &Ctx,
6865 const llvm::DenseMap<Sema::TypeTagMagicValue,
6866 Sema::TypeTagData> *MagicValues,
6867 bool &FoundWrongKind,
6868 Sema::TypeTagData &TypeInfo) {
6869 FoundWrongKind = false;
6870
6871 // Variable declaration that has type_tag_for_datatype attribute.
6872 const ValueDecl *VD = NULL;
6873
6874 uint64_t MagicValue;
6875
6876 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6877 return false;
6878
6879 if (VD) {
6880 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6881 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6882 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6883 I != E; ++I) {
6884 if (I->getArgumentKind() != ArgumentKind) {
6885 FoundWrongKind = true;
6886 return false;
6887 }
6888 TypeInfo.Type = I->getMatchingCType();
6889 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6890 TypeInfo.MustBeNull = I->getMustBeNull();
6891 return true;
6892 }
6893 return false;
6894 }
6895
6896 if (!MagicValues)
6897 return false;
6898
6899 llvm::DenseMap<Sema::TypeTagMagicValue,
6900 Sema::TypeTagData>::const_iterator I =
6901 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6902 if (I == MagicValues->end())
6903 return false;
6904
6905 TypeInfo = I->second;
6906 return true;
6907}
6908} // unnamed namespace
6909
6910void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6911 uint64_t MagicValue, QualType Type,
6912 bool LayoutCompatible,
6913 bool MustBeNull) {
6914 if (!TypeTagForDatatypeMagicValues)
6915 TypeTagForDatatypeMagicValues.reset(
6916 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6917
6918 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6919 (*TypeTagForDatatypeMagicValues)[Magic] =
6920 TypeTagData(Type, LayoutCompatible, MustBeNull);
6921}
6922
6923namespace {
6924bool IsSameCharType(QualType T1, QualType T2) {
6925 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6926 if (!BT1)
6927 return false;
6928
6929 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6930 if (!BT2)
6931 return false;
6932
6933 BuiltinType::Kind T1Kind = BT1->getKind();
6934 BuiltinType::Kind T2Kind = BT2->getKind();
6935
6936 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6937 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6938 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6939 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6940}
6941} // unnamed namespace
6942
6943void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6944 const Expr * const *ExprArgs) {
6945 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6946 bool IsPointerAttr = Attr->getIsPointer();
6947
6948 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6949 bool FoundWrongKind;
6950 TypeTagData TypeInfo;
6951 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6952 TypeTagForDatatypeMagicValues.get(),
6953 FoundWrongKind, TypeInfo)) {
6954 if (FoundWrongKind)
6955 Diag(TypeTagExpr->getExprLoc(),
6956 diag::warn_type_tag_for_datatype_wrong_kind)
6957 << TypeTagExpr->getSourceRange();
6958 return;
6959 }
6960
6961 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6962 if (IsPointerAttr) {
6963 // Skip implicit cast of pointer to `void *' (as a function argument).
6964 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006965 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006966 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006967 ArgumentExpr = ICE->getSubExpr();
6968 }
6969 QualType ArgumentType = ArgumentExpr->getType();
6970
6971 // Passing a `void*' pointer shouldn't trigger a warning.
6972 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6973 return;
6974
6975 if (TypeInfo.MustBeNull) {
6976 // Type tag with matching void type requires a null pointer.
6977 if (!ArgumentExpr->isNullPointerConstant(Context,
6978 Expr::NPC_ValueDependentIsNotNull)) {
6979 Diag(ArgumentExpr->getExprLoc(),
6980 diag::warn_type_safety_null_pointer_required)
6981 << ArgumentKind->getName()
6982 << ArgumentExpr->getSourceRange()
6983 << TypeTagExpr->getSourceRange();
6984 }
6985 return;
6986 }
6987
6988 QualType RequiredType = TypeInfo.Type;
6989 if (IsPointerAttr)
6990 RequiredType = Context.getPointerType(RequiredType);
6991
6992 bool mismatch = false;
6993 if (!TypeInfo.LayoutCompatible) {
6994 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6995
6996 // C++11 [basic.fundamental] p1:
6997 // Plain char, signed char, and unsigned char are three distinct types.
6998 //
6999 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7000 // char' depending on the current char signedness mode.
7001 if (mismatch)
7002 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7003 RequiredType->getPointeeType())) ||
7004 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7005 mismatch = false;
7006 } else
7007 if (IsPointerAttr)
7008 mismatch = !isLayoutCompatible(Context,
7009 ArgumentType->getPointeeType(),
7010 RequiredType->getPointeeType());
7011 else
7012 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7013
7014 if (mismatch)
7015 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7016 << ArgumentType << ArgumentKind->getName()
7017 << TypeInfo.LayoutCompatible << RequiredType
7018 << ArgumentExpr->getSourceRange()
7019 << TypeTagExpr->getSourceRange();
7020}