blob: 91ba91e4f5317a1c9e05b7383fb88da4ddb4b143 [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"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#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"
Stephen Hines651f13c2014-04-23 16:59:28 -070035#include "llvm/ADT/STLExtras.h"
Richard Smith0e218972013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#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 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.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
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700104 ExprResult Arg(TheCall->getArg(0));
Richard Smith5154dce2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700109 TheCall->setArg(0, Arg.get());
Richard Smith5154dce2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Stephen Hines176edba2014-12-01 14:53:08 -0800114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
John McCall60d7b3a2010-08-24 06:29:42 +0000142ExprResult
Stephen Hines176edba2014-12-01 14:53:08 -0800143Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
144 CallExpr *TheCall) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700145 ExprResult TheCallResult(TheCall);
Douglas Gregor2def4832008-11-17 20:34:05 +0000146
Chris Lattner946928f2010-10-01 23:23:24 +0000147 // Find out if any arguments are required to be integer constant expressions.
148 unsigned ICEArguments = 0;
149 ASTContext::GetBuiltinTypeError Error;
150 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
151 if (Error != ASTContext::GE_None)
152 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
153
154 // If any arguments are required to be ICE's, check and diagnose.
155 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
156 // Skip arguments not required to be ICE's.
157 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
158
159 llvm::APSInt Result;
160 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
161 return true;
162 ICEArguments &= ~(1 << ArgNo);
163 }
164
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000166 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000167 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000168 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000169 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000172 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000173 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinVAStart(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800177 case Builtin::BI__va_start: {
178 switch (Context.getTargetInfo().getTriple().getArch()) {
179 case llvm::Triple::arm:
180 case llvm::Triple::thumb:
181 if (SemaBuiltinVAStartARM(TheCall))
182 return ExprError();
183 break;
184 default:
185 if (SemaBuiltinVAStart(TheCall))
186 return ExprError();
187 break;
188 }
189 break;
190 }
Chris Lattner1b9a0792007-12-20 00:26:33 +0000191 case Builtin::BI__builtin_isgreater:
192 case Builtin::BI__builtin_isgreaterequal:
193 case Builtin::BI__builtin_isless:
194 case Builtin::BI__builtin_islessequal:
195 case Builtin::BI__builtin_islessgreater:
196 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000197 if (SemaBuiltinUnorderedCompare(TheCall))
198 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000199 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000200 case Builtin::BI__builtin_fpclassify:
201 if (SemaBuiltinFPClassification(TheCall, 6))
202 return ExprError();
203 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000204 case Builtin::BI__builtin_isfinite:
205 case Builtin::BI__builtin_isinf:
206 case Builtin::BI__builtin_isinf_sign:
207 case Builtin::BI__builtin_isnan:
208 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000209 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000210 return ExprError();
211 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000212 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000213 return SemaBuiltinShuffleVector(TheCall);
214 // TheCall will be freed by the smart pointer here, but that's fine, since
215 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000216 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000217 if (SemaBuiltinPrefetch(TheCall))
218 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000219 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800220 case Builtin::BI__assume:
221 case Builtin::BI__builtin_assume:
222 if (SemaBuiltinAssume(TheCall))
223 return ExprError();
224 break;
225 case Builtin::BI__builtin_assume_aligned:
226 if (SemaBuiltinAssumeAligned(TheCall))
227 return ExprError();
228 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000229 case Builtin::BI__builtin_object_size:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700230 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000231 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000232 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000233 case Builtin::BI__builtin_longjmp:
234 if (SemaBuiltinLongjmp(TheCall))
235 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000236 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000237
238 case Builtin::BI__builtin_classify_type:
239 if (checkArgCount(*this, TheCall, 1)) return true;
240 TheCall->setType(Context.IntTy);
241 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000242 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000243 if (checkArgCount(*this, TheCall, 1)) return true;
244 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000245 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000246 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_fetch_and_add_1:
248 case Builtin::BI__sync_fetch_and_add_2:
249 case Builtin::BI__sync_fetch_and_add_4:
250 case Builtin::BI__sync_fetch_and_add_8:
251 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000252 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000253 case Builtin::BI__sync_fetch_and_sub_1:
254 case Builtin::BI__sync_fetch_and_sub_2:
255 case Builtin::BI__sync_fetch_and_sub_4:
256 case Builtin::BI__sync_fetch_and_sub_8:
257 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000258 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000259 case Builtin::BI__sync_fetch_and_or_1:
260 case Builtin::BI__sync_fetch_and_or_2:
261 case Builtin::BI__sync_fetch_and_or_4:
262 case Builtin::BI__sync_fetch_and_or_8:
263 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000264 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000265 case Builtin::BI__sync_fetch_and_and_1:
266 case Builtin::BI__sync_fetch_and_and_2:
267 case Builtin::BI__sync_fetch_and_and_4:
268 case Builtin::BI__sync_fetch_and_and_8:
269 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000270 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000271 case Builtin::BI__sync_fetch_and_xor_1:
272 case Builtin::BI__sync_fetch_and_xor_2:
273 case Builtin::BI__sync_fetch_and_xor_4:
274 case Builtin::BI__sync_fetch_and_xor_8:
275 case Builtin::BI__sync_fetch_and_xor_16:
Stephen Hines176edba2014-12-01 14:53:08 -0800276 case Builtin::BI__sync_fetch_and_nand:
277 case Builtin::BI__sync_fetch_and_nand_1:
278 case Builtin::BI__sync_fetch_and_nand_2:
279 case Builtin::BI__sync_fetch_and_nand_4:
280 case Builtin::BI__sync_fetch_and_nand_8:
281 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000282 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000283 case Builtin::BI__sync_add_and_fetch_1:
284 case Builtin::BI__sync_add_and_fetch_2:
285 case Builtin::BI__sync_add_and_fetch_4:
286 case Builtin::BI__sync_add_and_fetch_8:
287 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000288 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000289 case Builtin::BI__sync_sub_and_fetch_1:
290 case Builtin::BI__sync_sub_and_fetch_2:
291 case Builtin::BI__sync_sub_and_fetch_4:
292 case Builtin::BI__sync_sub_and_fetch_8:
293 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000294 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000295 case Builtin::BI__sync_and_and_fetch_1:
296 case Builtin::BI__sync_and_and_fetch_2:
297 case Builtin::BI__sync_and_and_fetch_4:
298 case Builtin::BI__sync_and_and_fetch_8:
299 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000300 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000301 case Builtin::BI__sync_or_and_fetch_1:
302 case Builtin::BI__sync_or_and_fetch_2:
303 case Builtin::BI__sync_or_and_fetch_4:
304 case Builtin::BI__sync_or_and_fetch_8:
305 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000306 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000307 case Builtin::BI__sync_xor_and_fetch_1:
308 case Builtin::BI__sync_xor_and_fetch_2:
309 case Builtin::BI__sync_xor_and_fetch_4:
310 case Builtin::BI__sync_xor_and_fetch_8:
311 case Builtin::BI__sync_xor_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -0800312 case Builtin::BI__sync_nand_and_fetch:
313 case Builtin::BI__sync_nand_and_fetch_1:
314 case Builtin::BI__sync_nand_and_fetch_2:
315 case Builtin::BI__sync_nand_and_fetch_4:
316 case Builtin::BI__sync_nand_and_fetch_8:
317 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000318 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000319 case Builtin::BI__sync_val_compare_and_swap_1:
320 case Builtin::BI__sync_val_compare_and_swap_2:
321 case Builtin::BI__sync_val_compare_and_swap_4:
322 case Builtin::BI__sync_val_compare_and_swap_8:
323 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000324 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000325 case Builtin::BI__sync_bool_compare_and_swap_1:
326 case Builtin::BI__sync_bool_compare_and_swap_2:
327 case Builtin::BI__sync_bool_compare_and_swap_4:
328 case Builtin::BI__sync_bool_compare_and_swap_8:
329 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000330 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000331 case Builtin::BI__sync_lock_test_and_set_1:
332 case Builtin::BI__sync_lock_test_and_set_2:
333 case Builtin::BI__sync_lock_test_and_set_4:
334 case Builtin::BI__sync_lock_test_and_set_8:
335 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000336 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000337 case Builtin::BI__sync_lock_release_1:
338 case Builtin::BI__sync_lock_release_2:
339 case Builtin::BI__sync_lock_release_4:
340 case Builtin::BI__sync_lock_release_8:
341 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000342 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000343 case Builtin::BI__sync_swap_1:
344 case Builtin::BI__sync_swap_2:
345 case Builtin::BI__sync_swap_4:
346 case Builtin::BI__sync_swap_8:
347 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000348 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000349#define BUILTIN(ID, TYPE, ATTRS)
350#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
351 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000352 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000353#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000354 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000355 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000356 return ExprError();
357 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000358 case Builtin::BI__builtin_addressof:
359 if (SemaBuiltinAddressof(*this, TheCall))
360 return ExprError();
361 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700362 case Builtin::BI__builtin_operator_new:
363 case Builtin::BI__builtin_operator_delete:
364 if (!getLangOpts().CPlusPlus) {
365 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
366 << (BuiltinID == Builtin::BI__builtin_operator_new
367 ? "__builtin_operator_new"
368 : "__builtin_operator_delete")
369 << "C++";
370 return ExprError();
371 }
372 // CodeGen assumes it can find the global new and delete to call,
373 // so ensure that they are declared.
374 DeclareGlobalNewDelete();
375 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800376
377 // check secure string manipulation functions where overflows
378 // are detectable at compile time
379 case Builtin::BI__builtin___memcpy_chk:
380 case Builtin::BI__builtin___memmove_chk:
381 case Builtin::BI__builtin___memset_chk:
382 case Builtin::BI__builtin___strlcat_chk:
383 case Builtin::BI__builtin___strlcpy_chk:
384 case Builtin::BI__builtin___strncat_chk:
385 case Builtin::BI__builtin___strncpy_chk:
386 case Builtin::BI__builtin___stpncpy_chk:
387 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
388 break;
389 case Builtin::BI__builtin___memccpy_chk:
390 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
391 break;
392 case Builtin::BI__builtin___snprintf_chk:
393 case Builtin::BI__builtin___vsnprintf_chk:
394 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
395 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000396 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700397
Nate Begeman26a31422010-06-08 02:47:44 +0000398 // Since the target specific builtins for each arch overlap, only check those
399 // of the arch we are compiling for.
400 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000401 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000402 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -0700403 case llvm::Triple::armeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000404 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -0700405 case llvm::Triple::thumbeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000406 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
407 return ExprError();
408 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000409 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700410 case llvm::Triple::aarch64_be:
Tim Northoverb793f0d2013-08-01 09:23:19 +0000411 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
412 return ExprError();
413 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000414 case llvm::Triple::mips:
415 case llvm::Triple::mipsel:
416 case llvm::Triple::mips64:
417 case llvm::Triple::mips64el:
418 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
419 return ExprError();
420 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700421 case llvm::Triple::x86:
422 case llvm::Triple::x86_64:
423 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
424 return ExprError();
425 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000426 default:
427 break;
428 }
429 }
430
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000431 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000432}
433
Nate Begeman61eecf52010-06-14 05:21:25 +0000434// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700435static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000436 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700437 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-11-08 01:16:11 +0000438 switch (Type.getEltType()) {
439 case NeonTypeFlags::Int8:
440 case NeonTypeFlags::Poly8:
441 return shift ? 7 : (8 << IsQuad) - 1;
442 case NeonTypeFlags::Int16:
443 case NeonTypeFlags::Poly16:
444 return shift ? 15 : (4 << IsQuad) - 1;
445 case NeonTypeFlags::Int32:
446 return shift ? 31 : (2 << IsQuad) - 1;
447 case NeonTypeFlags::Int64:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000448 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000449 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700450 case NeonTypeFlags::Poly128:
451 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-11-08 01:16:11 +0000452 case NeonTypeFlags::Float16:
453 assert(!shift && "cannot shift float types!");
454 return (4 << IsQuad) - 1;
455 case NeonTypeFlags::Float32:
456 assert(!shift && "cannot shift float types!");
457 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000458 case NeonTypeFlags::Float64:
459 assert(!shift && "cannot shift float types!");
460 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000461 }
David Blaikie7530c032012-01-17 06:56:22 +0000462 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000463}
464
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000465/// getNeonEltType - Return the QualType corresponding to the elements of
466/// the vector type specified by the NeonTypeFlags. This is used to check
467/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000468static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700469 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000470 switch (Flags.getEltType()) {
471 case NeonTypeFlags::Int8:
472 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
473 case NeonTypeFlags::Int16:
474 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
475 case NeonTypeFlags::Int32:
476 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
477 case NeonTypeFlags::Int64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700478 if (IsInt64Long)
479 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
480 else
481 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
482 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000483 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700484 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000485 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700486 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000487 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700488 return Context.UnsignedLongTy;
489 case NeonTypeFlags::Poly128:
490 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000491 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000492 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000493 case NeonTypeFlags::Float32:
494 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000495 case NeonTypeFlags::Float64:
496 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000497 }
David Blaikie7530c032012-01-17 06:56:22 +0000498 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000499}
500
Stephen Hines651f13c2014-04-23 16:59:28 -0700501bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000502 llvm::APSInt Result;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000503 uint64_t mask = 0;
504 unsigned TV = 0;
505 int PtrArgNum = -1;
506 bool HasConstPtr = false;
507 switch (BuiltinID) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700508#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000509#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700510#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000511 }
512
513 // For NEON intrinsics which are overloaded on vector element type, validate
514 // the immediate which specifies which variant to emit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700515 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000516 if (mask) {
517 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
518 return true;
519
520 TV = Result.getLimitedValue(64);
521 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
522 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Stephen Hines651f13c2014-04-23 16:59:28 -0700523 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-08-01 09:23:19 +0000524 }
525
526 if (PtrArgNum >= 0) {
527 // Check that pointer arguments have the specified type.
528 Expr *Arg = TheCall->getArg(PtrArgNum);
529 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
530 Arg = ICE->getSubExpr();
531 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
532 QualType RHSTy = RHS.get()->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700533
534 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Stephen Hines176edba2014-12-01 14:53:08 -0800535 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Stephen Hines651f13c2014-04-23 16:59:28 -0700536 bool IsInt64Long =
537 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
538 QualType EltTy =
539 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000540 if (HasConstPtr)
541 EltTy = EltTy.withConst();
542 QualType LHSTy = Context.getPointerType(EltTy);
543 AssignConvertType ConvTy;
544 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
545 if (RHS.isInvalid())
546 return true;
547 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
548 RHS.get(), AA_Assigning))
549 return true;
550 }
551
552 // For NEON intrinsics which take an immediate value as part of the
553 // instruction, range check them here.
554 unsigned i = 0, l = 0, u = 0;
555 switch (BuiltinID) {
556 default:
557 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700558#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000559#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700560#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000561 }
Tim Northoverb793f0d2013-08-01 09:23:19 +0000562
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700563 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700564}
565
566bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
567 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000568 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700569 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700570 BuiltinID == ARM::BI__builtin_arm_strex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700571 BuiltinID == ARM::BI__builtin_arm_stlex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700572 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700573 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
574 BuiltinID == AArch64::BI__builtin_arm_strex ||
575 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000576 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700577 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700578 BuiltinID == ARM::BI__builtin_arm_ldaex ||
579 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
580 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover09df2b02013-07-16 09:47:53 +0000581
582 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
583
584 // Ensure that we have the proper number of arguments.
585 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
586 return true;
587
588 // Inspect the pointer argument of the atomic builtin. This should always be
589 // a pointer type, whose element is an integral scalar or pointer type.
590 // Because it is a pointer type, we don't have to worry about any implicit
591 // casts here.
592 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
593 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
594 if (PointerArgRes.isInvalid())
595 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700596 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000597
598 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
599 if (!pointerType) {
600 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
601 << PointerArg->getType() << PointerArg->getSourceRange();
602 return true;
603 }
604
605 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
606 // task is to insert the appropriate casts into the AST. First work out just
607 // what the appropriate type is.
608 QualType ValType = pointerType->getPointeeType();
609 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
610 if (IsLdrex)
611 AddrType.addConst();
612
613 // Issue a warning if the cast is dodgy.
614 CastKind CastNeeded = CK_NoOp;
615 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
616 CastNeeded = CK_BitCast;
617 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
618 << PointerArg->getType()
619 << Context.getPointerType(AddrType)
620 << AA_Passing << PointerArg->getSourceRange();
621 }
622
623 // Finally, do the cast and replace the argument with the corrected version.
624 AddrType = Context.getPointerType(AddrType);
625 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
626 if (PointerArgRes.isInvalid())
627 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700628 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000629
630 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
631
632 // In general, we allow ints, floats and pointers to be loaded and stored.
633 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
634 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
635 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
636 << PointerArg->getType() << PointerArg->getSourceRange();
637 return true;
638 }
639
640 // But ARM doesn't have instructions to deal with 128-bit versions.
Stephen Hines651f13c2014-04-23 16:59:28 -0700641 if (Context.getTypeSize(ValType) > MaxWidth) {
642 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-07-16 09:47:53 +0000643 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
644 << PointerArg->getType() << PointerArg->getSourceRange();
645 return true;
646 }
647
648 switch (ValType.getObjCLifetime()) {
649 case Qualifiers::OCL_None:
650 case Qualifiers::OCL_ExplicitNone:
651 // okay
652 break;
653
654 case Qualifiers::OCL_Weak:
655 case Qualifiers::OCL_Strong:
656 case Qualifiers::OCL_Autoreleasing:
657 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
658 << ValType << PointerArg->getSourceRange();
659 return true;
660 }
661
662
663 if (IsLdrex) {
664 TheCall->setType(ValType);
665 return false;
666 }
667
668 // Initialize the argument to be stored.
669 ExprResult ValArg = TheCall->getArg(0);
670 InitializedEntity Entity = InitializedEntity::InitializeParameter(
671 Context, ValType, /*consume*/ false);
672 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
673 if (ValArg.isInvalid())
674 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000675 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000676
677 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
678 // but the custom checker bypasses all default analysis.
679 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000680 return false;
681}
682
Nate Begeman26a31422010-06-08 02:47:44 +0000683bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000684 llvm::APSInt Result;
685
Tim Northover09df2b02013-07-16 09:47:53 +0000686 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700687 BuiltinID == ARM::BI__builtin_arm_ldaex ||
688 BuiltinID == ARM::BI__builtin_arm_strex ||
689 BuiltinID == ARM::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700690 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000691 }
692
Stephen Hines176edba2014-12-01 14:53:08 -0800693 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
694 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
695 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
696 }
697
Stephen Hines651f13c2014-04-23 16:59:28 -0700698 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
699 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000700
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700701 // For intrinsics which take an immediate value as part of the instruction,
702 // range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000703 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000704 switch (BuiltinID) {
705 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000706 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
707 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000708 case ARM::BI__builtin_arm_vcvtr_f:
709 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000710 case ARM::BI__builtin_arm_dmb:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700711 case ARM::BI__builtin_arm_dsb:
Stephen Hines176edba2014-12-01 14:53:08 -0800712 case ARM::BI__builtin_arm_isb:
713 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700714 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000715
Nate Begeman99c40bb2010-08-03 21:32:34 +0000716 // FIXME: VFP Intrinsics should error if VFP not present.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700717 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssond406bf02009-08-16 01:56:34 +0000718}
Daniel Dunbarde454282008-10-02 18:44:07 +0000719
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700720bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Stephen Hines651f13c2014-04-23 16:59:28 -0700721 CallExpr *TheCall) {
722 llvm::APSInt Result;
723
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700724 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700725 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
726 BuiltinID == AArch64::BI__builtin_arm_strex ||
727 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700728 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
729 }
730
Stephen Hines176edba2014-12-01 14:53:08 -0800731 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
732 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
733 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
734 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
735 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
736 }
737
Stephen Hines651f13c2014-04-23 16:59:28 -0700738 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
739 return true;
740
Stephen Hines176edba2014-12-01 14:53:08 -0800741 // For intrinsics which take an immediate value as part of the instruction,
742 // range check them here.
743 unsigned i = 0, l = 0, u = 0;
744 switch (BuiltinID) {
745 default: return false;
746 case AArch64::BI__builtin_arm_dmb:
747 case AArch64::BI__builtin_arm_dsb:
748 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
749 }
750
751 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700752}
753
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000754bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
755 unsigned i = 0, l = 0, u = 0;
756 switch (BuiltinID) {
757 default: return false;
758 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
759 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000760 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
761 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
762 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
763 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
764 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700765 }
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000766
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700767 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000768}
769
Stephen Hines651f13c2014-04-23 16:59:28 -0700770bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
771 switch (BuiltinID) {
772 case X86::BI_mm_prefetch:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700773 // This is declared to take (const char*, int)
774 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Stephen Hines651f13c2014-04-23 16:59:28 -0700775 }
776 return false;
777}
778
Richard Smith831421f2012-06-25 20:30:08 +0000779/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
780/// parameter with the FormatAttr's correct format_idx and firstDataArg.
781/// Returns true when the format fits the function and the FormatStringInfo has
782/// been populated.
783bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
784 FormatStringInfo *FSI) {
785 FSI->HasVAListArg = Format->getFirstArg() == 0;
786 FSI->FormatIdx = Format->getFormatIdx() - 1;
787 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000788
Richard Smith831421f2012-06-25 20:30:08 +0000789 // The way the format attribute works in GCC, the implicit this argument
790 // of member functions is counted. However, it doesn't appear in our own
791 // lists, so decrement format_idx in that case.
792 if (IsCXXMember) {
793 if(FSI->FormatIdx == 0)
794 return false;
795 --FSI->FormatIdx;
796 if (FSI->FirstDataArg != 0)
797 --FSI->FirstDataArg;
798 }
799 return true;
800}
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Stephen Hines651f13c2014-04-23 16:59:28 -0700802/// Checks if a the given expression evaluates to null.
803///
804/// \brief Returns true if the value evaluates to null.
805static bool CheckNonNullExpr(Sema &S,
806 const Expr *Expr) {
807 // As a special case, transparent unions initialized with zero are
808 // considered null for the purposes of the nonnull attribute.
809 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
810 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
811 if (const CompoundLiteralExpr *CLE =
812 dyn_cast<CompoundLiteralExpr>(Expr))
813 if (const InitListExpr *ILE =
814 dyn_cast<InitListExpr>(CLE->getInitializer()))
815 Expr = ILE->getInit(0);
816 }
817
818 bool Result;
819 return (!Expr->isValueDependent() &&
820 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
821 !Result);
822}
823
824static void CheckNonNullArgument(Sema &S,
825 const Expr *ArgExpr,
826 SourceLocation CallSiteLoc) {
827 if (CheckNonNullExpr(S, ArgExpr))
828 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
829}
830
Stephen Hines176edba2014-12-01 14:53:08 -0800831bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
832 FormatStringInfo FSI;
833 if ((GetFormatStringType(Format) == FST_NSString) &&
834 getFormatStringInfo(Format, false, &FSI)) {
835 Idx = FSI.FormatIdx;
836 return true;
837 }
838 return false;
839}
840/// \brief Diagnose use of %s directive in an NSString which is being passed
841/// as formatting string to formatting method.
842static void
843DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
844 const NamedDecl *FDecl,
845 Expr **Args,
846 unsigned NumArgs) {
847 unsigned Idx = 0;
848 bool Format = false;
849 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
850 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
851 Idx = 2;
852 Format = true;
853 }
854 else
855 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
856 if (S.GetFormatNSStringIdx(I, Idx)) {
857 Format = true;
858 break;
859 }
860 }
861 if (!Format || NumArgs <= Idx)
862 return;
863 const Expr *FormatExpr = Args[Idx];
864 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
865 FormatExpr = CSCE->getSubExpr();
866 const StringLiteral *FormatString;
867 if (const ObjCStringLiteral *OSL =
868 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
869 FormatString = OSL->getString();
870 else
871 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
872 if (!FormatString)
873 return;
874 if (S.FormatStringHasSArg(FormatString)) {
875 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
876 << "%s" << 1 << 1;
877 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
878 << FDecl->getDeclName();
879 }
880}
881
Stephen Hines651f13c2014-04-23 16:59:28 -0700882static void CheckNonNullArguments(Sema &S,
883 const NamedDecl *FDecl,
Stephen Hines176edba2014-12-01 14:53:08 -0800884 ArrayRef<const Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -0700885 SourceLocation CallSiteLoc) {
886 // Check the attributes attached to the method/function itself.
Stephen Hines176edba2014-12-01 14:53:08 -0800887 llvm::SmallBitVector NonNullArgs;
Stephen Hines651f13c2014-04-23 16:59:28 -0700888 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800889 if (!NonNull->args_size()) {
890 // Easy case: all pointer arguments are nonnull.
891 for (const auto *Arg : Args)
892 if (S.isValidPointerAttrType(Arg->getType()))
893 CheckNonNullArgument(S, Arg, CallSiteLoc);
894 return;
895 }
896
897 for (unsigned Val : NonNull->args()) {
898 if (Val >= Args.size())
899 continue;
900 if (NonNullArgs.empty())
901 NonNullArgs.resize(Args.size());
902 NonNullArgs.set(Val);
903 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700904 }
905
906 // Check the attributes on the parameters.
907 ArrayRef<ParmVarDecl*> parms;
908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
909 parms = FD->parameters();
910 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
911 parms = MD->parameters();
912
Stephen Hines176edba2014-12-01 14:53:08 -0800913 unsigned ArgIndex = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700914 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Stephen Hines176edba2014-12-01 14:53:08 -0800915 I != E; ++I, ++ArgIndex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700916 const ParmVarDecl *PVD = *I;
Stephen Hines176edba2014-12-01 14:53:08 -0800917 if (PVD->hasAttr<NonNullAttr>() ||
918 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
919 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -0700920 }
Stephen Hines176edba2014-12-01 14:53:08 -0800921
922 // In case this is a variadic call, check any remaining arguments.
923 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
924 if (NonNullArgs[ArgIndex])
925 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -0700926}
927
Richard Smith831421f2012-06-25 20:30:08 +0000928/// Handles the checks for format strings, non-POD arguments to vararg
929/// functions, and NULL arguments passed to non-NULL parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -0700930void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
931 unsigned NumParams, bool IsMemberFunction,
932 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +0000933 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000934 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000935 if (CurContext->isDependentContext())
936 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000937
Ted Kremenekc82faca2010-09-09 04:33:05 +0000938 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000939 llvm::SmallBitVector CheckedVarArgs;
940 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700941 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000942 // Only create vector if there are format attributes.
943 CheckedVarArgs.resize(Args.size());
944
Stephen Hines651f13c2014-04-23 16:59:28 -0700945 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +0000946 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000947 }
Richard Smith0e218972013-08-05 18:49:43 +0000948 }
Richard Smith831421f2012-06-25 20:30:08 +0000949
950 // Refuse POD arguments that weren't caught by the format string
951 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000952 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700953 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000954 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000955 if (const Expr *Arg = Args[ArgIdx]) {
956 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
957 checkVariadicArgument(Arg, CallType);
958 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000959 }
Richard Smith0e218972013-08-05 18:49:43 +0000960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Richard Trieu0538f0e2013-06-22 00:20:41 +0000962 if (FDecl) {
Stephen Hines176edba2014-12-01 14:53:08 -0800963 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000964
Richard Trieu0538f0e2013-06-22 00:20:41 +0000965 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -0700966 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
967 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000968 }
Richard Smith831421f2012-06-25 20:30:08 +0000969}
970
971/// CheckConstructorCall - Check a constructor call for correctness and safety
972/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000973void Sema::CheckConstructorCall(FunctionDecl *FDecl,
974 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000975 const FunctionProtoType *Proto,
976 SourceLocation Loc) {
977 VariadicCallType CallType =
978 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -0700979 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-06-25 20:30:08 +0000980 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
981}
982
983/// CheckFunctionCall - Check a direct function call for various correctness
984/// and safety properties not strictly enforced by the C type system.
985bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
986 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000987 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
988 isa<CXXMethodDecl>(FDecl);
989 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
990 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000991 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
992 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700993 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000994 Expr** Args = TheCall->getArgs();
995 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000996 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000997 // If this is a call to a member operator, hide the first argument
998 // from checkCall.
999 // FIXME: Our choice of AST representation here is less than ideal.
1000 ++Args;
1001 --NumArgs;
1002 }
Stephen Hines176edba2014-12-01 14:53:08 -08001003 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith831421f2012-06-25 20:30:08 +00001004 IsMemberFunction, TheCall->getRParenLoc(),
1005 TheCall->getCallee()->getSourceRange(), CallType);
1006
1007 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1008 // None of the checks below are needed for functions that don't have
1009 // simple names (e.g., C++ conversion functions).
1010 if (!FnInfo)
1011 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001012
Stephen Hines651f13c2014-04-23 16:59:28 -07001013 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Stephen Hines176edba2014-12-01 14:53:08 -08001014 if (getLangOpts().ObjC1)
1015 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Stephen Hines651f13c2014-04-23 16:59:28 -07001016
Anna Zaks0a151a12012-01-17 00:37:07 +00001017 unsigned CMId = FDecl->getMemoryFunctionKind();
1018 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +00001019 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001020
Anna Zaksd9b859a2012-01-13 21:52:01 +00001021 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +00001022 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001023 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +00001024 else if (CMId == Builtin::BIstrncat)
1025 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +00001026 else
Anna Zaks0a151a12012-01-17 00:37:07 +00001027 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001028
Anders Carlssond406bf02009-08-16 01:56:34 +00001029 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001030}
1031
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001032bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001033 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +00001034 VariadicCallType CallType =
1035 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001036
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001037 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +00001038 /*IsMemberFunction=*/false,
1039 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001040
1041 return false;
1042}
1043
Richard Trieuf462b012013-06-20 21:03:13 +00001044bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1045 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001046 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1047 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +00001048 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001050 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +00001051 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +00001052 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Richard Trieuf462b012013-06-20 21:03:13 +00001054 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +00001055 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +00001056 CallType = VariadicDoesNotApply;
1057 } else if (Ty->isBlockPointerType()) {
1058 CallType = VariadicBlock;
1059 } else { // Ty->isFunctionPointerType()
1060 CallType = VariadicFunction;
1061 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001062 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +00001063
Stephen Hines176edba2014-12-01 14:53:08 -08001064 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1065 TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001066 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +00001067 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -07001068
Anders Carlssond406bf02009-08-16 01:56:34 +00001069 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001070}
1071
Richard Trieu0538f0e2013-06-22 00:20:41 +00001072/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1073/// such as function pointers returned from functions.
1074bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001075 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu0538f0e2013-06-22 00:20:41 +00001076 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001077 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +00001078
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001079 checkCall(/*FDecl=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001080 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001081 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +00001082 TheCall->getCallee()->getSourceRange(), CallType);
1083
1084 return false;
1085}
1086
Stephen Hines651f13c2014-04-23 16:59:28 -07001087static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1088 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1089 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1090 return false;
1091
1092 switch (Op) {
1093 case AtomicExpr::AO__c11_atomic_init:
1094 llvm_unreachable("There is no ordering argument for an init");
1095
1096 case AtomicExpr::AO__c11_atomic_load:
1097 case AtomicExpr::AO__atomic_load_n:
1098 case AtomicExpr::AO__atomic_load:
1099 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1100 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1101
1102 case AtomicExpr::AO__c11_atomic_store:
1103 case AtomicExpr::AO__atomic_store:
1104 case AtomicExpr::AO__atomic_store_n:
1105 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1106 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1107 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1108
1109 default:
1110 return true;
1111 }
1112}
1113
Richard Smithff34d402012-04-12 05:08:17 +00001114ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1115 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +00001116 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1117 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +00001118
Richard Smithff34d402012-04-12 05:08:17 +00001119 // All these operations take one of the following forms:
1120 enum {
1121 // C __c11_atomic_init(A *, C)
1122 Init,
1123 // C __c11_atomic_load(A *, int)
1124 Load,
1125 // void __atomic_load(A *, CP, int)
1126 Copy,
1127 // C __c11_atomic_add(A *, M, int)
1128 Arithmetic,
1129 // C __atomic_exchange_n(A *, CP, int)
1130 Xchg,
1131 // void __atomic_exchange(A *, C *, CP, int)
1132 GNUXchg,
1133 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1134 C11CmpXchg,
1135 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1136 GNUCmpXchg
1137 } Form = Init;
1138 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1139 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1140 // where:
1141 // C is an appropriate type,
1142 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1143 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1144 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1145 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +00001146
Richard Smithff34d402012-04-12 05:08:17 +00001147 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1148 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1149 && "need to update code for modified C11 atomics");
1150 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1151 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1152 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1153 Op == AtomicExpr::AO__atomic_store_n ||
1154 Op == AtomicExpr::AO__atomic_exchange_n ||
1155 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1156 bool IsAddSub = false;
1157
1158 switch (Op) {
1159 case AtomicExpr::AO__c11_atomic_init:
1160 Form = Init;
1161 break;
1162
1163 case AtomicExpr::AO__c11_atomic_load:
1164 case AtomicExpr::AO__atomic_load_n:
1165 Form = Load;
1166 break;
1167
1168 case AtomicExpr::AO__c11_atomic_store:
1169 case AtomicExpr::AO__atomic_load:
1170 case AtomicExpr::AO__atomic_store:
1171 case AtomicExpr::AO__atomic_store_n:
1172 Form = Copy;
1173 break;
1174
1175 case AtomicExpr::AO__c11_atomic_fetch_add:
1176 case AtomicExpr::AO__c11_atomic_fetch_sub:
1177 case AtomicExpr::AO__atomic_fetch_add:
1178 case AtomicExpr::AO__atomic_fetch_sub:
1179 case AtomicExpr::AO__atomic_add_fetch:
1180 case AtomicExpr::AO__atomic_sub_fetch:
1181 IsAddSub = true;
1182 // Fall through.
1183 case AtomicExpr::AO__c11_atomic_fetch_and:
1184 case AtomicExpr::AO__c11_atomic_fetch_or:
1185 case AtomicExpr::AO__c11_atomic_fetch_xor:
1186 case AtomicExpr::AO__atomic_fetch_and:
1187 case AtomicExpr::AO__atomic_fetch_or:
1188 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00001189 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00001190 case AtomicExpr::AO__atomic_and_fetch:
1191 case AtomicExpr::AO__atomic_or_fetch:
1192 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00001193 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +00001194 Form = Arithmetic;
1195 break;
1196
1197 case AtomicExpr::AO__c11_atomic_exchange:
1198 case AtomicExpr::AO__atomic_exchange_n:
1199 Form = Xchg;
1200 break;
1201
1202 case AtomicExpr::AO__atomic_exchange:
1203 Form = GNUXchg;
1204 break;
1205
1206 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1207 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1208 Form = C11CmpXchg;
1209 break;
1210
1211 case AtomicExpr::AO__atomic_compare_exchange:
1212 case AtomicExpr::AO__atomic_compare_exchange_n:
1213 Form = GNUCmpXchg;
1214 break;
1215 }
1216
1217 // Check we have the right number of arguments.
1218 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +00001219 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001220 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001221 << TheCall->getCallee()->getSourceRange();
1222 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001223 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1224 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001225 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001226 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001227 << TheCall->getCallee()->getSourceRange();
1228 return ExprError();
1229 }
1230
Richard Smithff34d402012-04-12 05:08:17 +00001231 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001232 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001233 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1234 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1235 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001236 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001237 << Ptr->getType() << Ptr->getSourceRange();
1238 return ExprError();
1239 }
1240
Richard Smithff34d402012-04-12 05:08:17 +00001241 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1242 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1243 QualType ValType = AtomTy; // 'C'
1244 if (IsC11) {
1245 if (!AtomTy->isAtomicType()) {
1246 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1247 << Ptr->getType() << Ptr->getSourceRange();
1248 return ExprError();
1249 }
Richard Smithbc57b102012-09-15 06:09:58 +00001250 if (AtomTy.isConstQualified()) {
1251 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1252 << Ptr->getType() << Ptr->getSourceRange();
1253 return ExprError();
1254 }
Richard Smithff34d402012-04-12 05:08:17 +00001255 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001256 }
Eli Friedman276b0612011-10-11 02:20:01 +00001257
Richard Smithff34d402012-04-12 05:08:17 +00001258 // For an arithmetic operation, the implied arithmetic must be well-formed.
1259 if (Form == Arithmetic) {
1260 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1261 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1262 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1263 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1264 return ExprError();
1265 }
1266 if (!IsAddSub && !ValType->isIntegerType()) {
1267 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1268 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1269 return ExprError();
1270 }
1271 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1272 // For __atomic_*_n operations, the value type must be a scalar integral or
1273 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001274 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001275 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1276 return ExprError();
1277 }
1278
Eli Friedmana3d727b2013-09-11 03:49:34 +00001279 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1280 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001281 // For GNU atomics, require a trivially-copyable type. This is not part of
1282 // the GNU atomics specification, but we enforce it for sanity.
1283 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001284 << Ptr->getType() << Ptr->getSourceRange();
1285 return ExprError();
1286 }
1287
Richard Smithff34d402012-04-12 05:08:17 +00001288 // FIXME: For any builtin other than a load, the ValType must not be
1289 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001290
1291 switch (ValType.getObjCLifetime()) {
1292 case Qualifiers::OCL_None:
1293 case Qualifiers::OCL_ExplicitNone:
1294 // okay
1295 break;
1296
1297 case Qualifiers::OCL_Weak:
1298 case Qualifiers::OCL_Strong:
1299 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001300 // FIXME: Can this happen? By this point, ValType should be known
1301 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001302 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1303 << ValType << Ptr->getSourceRange();
1304 return ExprError();
1305 }
1306
1307 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001308 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001309 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001310 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001311 ResultType = Context.BoolTy;
1312
Richard Smithff34d402012-04-12 05:08:17 +00001313 // The type of a parameter passed 'by value'. In the GNU atomics, such
1314 // arguments are actually passed as pointers.
1315 QualType ByValType = ValType; // 'CP'
1316 if (!IsC11 && !IsN)
1317 ByValType = Ptr->getType();
1318
Eli Friedman276b0612011-10-11 02:20:01 +00001319 // The first argument --- the pointer --- has a fixed type; we
1320 // deduce the types of the rest of the arguments accordingly. Walk
1321 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001322 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001323 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001324 if (i < NumVals[Form] + 1) {
1325 switch (i) {
1326 case 1:
1327 // The second argument is the non-atomic operand. For arithmetic, this
1328 // is always passed by value, and for a compare_exchange it is always
1329 // passed by address. For the rest, GNU uses by-address and C11 uses
1330 // by-value.
1331 assert(Form != Load);
1332 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1333 Ty = ValType;
1334 else if (Form == Copy || Form == Xchg)
1335 Ty = ByValType;
1336 else if (Form == Arithmetic)
1337 Ty = Context.getPointerDiffType();
1338 else
1339 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1340 break;
1341 case 2:
1342 // The third argument to compare_exchange / GNU exchange is a
1343 // (pointer to a) desired value.
1344 Ty = ByValType;
1345 break;
1346 case 3:
1347 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1348 Ty = Context.BoolTy;
1349 break;
1350 }
Eli Friedman276b0612011-10-11 02:20:01 +00001351 } else {
1352 // The order(s) are always converted to int.
1353 Ty = Context.IntTy;
1354 }
Richard Smithff34d402012-04-12 05:08:17 +00001355
Eli Friedman276b0612011-10-11 02:20:01 +00001356 InitializedEntity Entity =
1357 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001358 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001359 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1360 if (Arg.isInvalid())
1361 return true;
1362 TheCall->setArg(i, Arg.get());
1363 }
1364
Richard Smithff34d402012-04-12 05:08:17 +00001365 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001366 SmallVector<Expr*, 5> SubExprs;
1367 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001368 switch (Form) {
1369 case Init:
1370 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001371 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001372 break;
1373 case Load:
1374 SubExprs.push_back(TheCall->getArg(1)); // Order
1375 break;
1376 case Copy:
1377 case Arithmetic:
1378 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001379 SubExprs.push_back(TheCall->getArg(2)); // Order
1380 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001381 break;
1382 case GNUXchg:
1383 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1384 SubExprs.push_back(TheCall->getArg(3)); // Order
1385 SubExprs.push_back(TheCall->getArg(1)); // Val1
1386 SubExprs.push_back(TheCall->getArg(2)); // Val2
1387 break;
1388 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001389 SubExprs.push_back(TheCall->getArg(3)); // Order
1390 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001391 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001392 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001393 break;
1394 case GNUCmpXchg:
1395 SubExprs.push_back(TheCall->getArg(4)); // Order
1396 SubExprs.push_back(TheCall->getArg(1)); // Val1
1397 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1398 SubExprs.push_back(TheCall->getArg(2)); // Val2
1399 SubExprs.push_back(TheCall->getArg(3)); // Weak
1400 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001401 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001402
1403 if (SubExprs.size() >= 2 && Form != Init) {
1404 llvm::APSInt Result(32);
1405 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1406 !isValidOrderingForOp(Result.getSExtValue(), Op))
1407 Diag(SubExprs[1]->getLocStart(),
1408 diag::warn_atomic_op_has_invalid_memory_order)
1409 << SubExprs[1]->getSourceRange();
1410 }
1411
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001412 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1413 SubExprs, ResultType, Op,
1414 TheCall->getRParenLoc());
1415
1416 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1417 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1418 Context.AtomicUsesUnsupportedLibcall(AE))
1419 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1420 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001421
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001422 return AE;
Eli Friedman276b0612011-10-11 02:20:01 +00001423}
1424
1425
John McCall5f8d6042011-08-27 01:09:30 +00001426/// checkBuiltinArgument - Given a call to a builtin function, perform
1427/// normal type-checking on the given argument, updating the call in
1428/// place. This is useful when a builtin function requires custom
1429/// type-checking for some of its arguments but not necessarily all of
1430/// them.
1431///
1432/// Returns true on error.
1433static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1434 FunctionDecl *Fn = E->getDirectCallee();
1435 assert(Fn && "builtin call without direct callee!");
1436
1437 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1438 InitializedEntity Entity =
1439 InitializedEntity::InitializeParameter(S.Context, Param);
1440
1441 ExprResult Arg = E->getArg(0);
1442 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1443 if (Arg.isInvalid())
1444 return true;
1445
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001446 E->setArg(ArgIndex, Arg.get());
John McCall5f8d6042011-08-27 01:09:30 +00001447 return false;
1448}
1449
Chris Lattner5caa3702009-05-08 06:58:22 +00001450/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1451/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1452/// type of its first argument. The main ActOnCallExpr routines have already
1453/// promoted the types of arguments because all of these calls are prototyped as
1454/// void(...).
1455///
1456/// This function goes through and does final semantic checking for these
1457/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001458ExprResult
1459Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001460 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001461 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1462 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1463
1464 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001465 if (TheCall->getNumArgs() < 1) {
1466 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1467 << 0 << 1 << TheCall->getNumArgs()
1468 << TheCall->getCallee()->getSourceRange();
1469 return ExprError();
1470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Chris Lattner5caa3702009-05-08 06:58:22 +00001472 // Inspect the first argument of the atomic builtin. This should always be
1473 // a pointer type, whose element is an integral scalar or pointer type.
1474 // Because it is a pointer type, we don't have to worry about any implicit
1475 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001476 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001477 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001478 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1479 if (FirstArgResult.isInvalid())
1480 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001481 FirstArg = FirstArgResult.get();
Eli Friedman8c382062012-01-23 02:35:22 +00001482 TheCall->setArg(0, FirstArg);
1483
John McCallf85e1932011-06-15 23:02:42 +00001484 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1485 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001486 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1487 << FirstArg->getType() << FirstArg->getSourceRange();
1488 return ExprError();
1489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
John McCallf85e1932011-06-15 23:02:42 +00001491 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001492 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001493 !ValType->isBlockPointerType()) {
1494 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1495 << FirstArg->getType() << FirstArg->getSourceRange();
1496 return ExprError();
1497 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001498
John McCallf85e1932011-06-15 23:02:42 +00001499 switch (ValType.getObjCLifetime()) {
1500 case Qualifiers::OCL_None:
1501 case Qualifiers::OCL_ExplicitNone:
1502 // okay
1503 break;
1504
1505 case Qualifiers::OCL_Weak:
1506 case Qualifiers::OCL_Strong:
1507 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001508 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001509 << ValType << FirstArg->getSourceRange();
1510 return ExprError();
1511 }
1512
John McCallb45ae252011-10-05 07:41:44 +00001513 // Strip any qualifiers off ValType.
1514 ValType = ValType.getUnqualifiedType();
1515
Chandler Carruth8d13d222010-07-18 20:54:12 +00001516 // The majority of builtins return a value, but a few have special return
1517 // types, so allow them to override appropriately below.
1518 QualType ResultType = ValType;
1519
Chris Lattner5caa3702009-05-08 06:58:22 +00001520 // We need to figure out which concrete builtin this maps onto. For example,
1521 // __sync_fetch_and_add with a 2 byte object turns into
1522 // __sync_fetch_and_add_2.
1523#define BUILTIN_ROW(x) \
1524 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1525 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Chris Lattner5caa3702009-05-08 06:58:22 +00001527 static const unsigned BuiltinIndices[][5] = {
1528 BUILTIN_ROW(__sync_fetch_and_add),
1529 BUILTIN_ROW(__sync_fetch_and_sub),
1530 BUILTIN_ROW(__sync_fetch_and_or),
1531 BUILTIN_ROW(__sync_fetch_and_and),
1532 BUILTIN_ROW(__sync_fetch_and_xor),
Stephen Hines176edba2014-12-01 14:53:08 -08001533 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Chris Lattner5caa3702009-05-08 06:58:22 +00001535 BUILTIN_ROW(__sync_add_and_fetch),
1536 BUILTIN_ROW(__sync_sub_and_fetch),
1537 BUILTIN_ROW(__sync_and_and_fetch),
1538 BUILTIN_ROW(__sync_or_and_fetch),
1539 BUILTIN_ROW(__sync_xor_and_fetch),
Stephen Hines176edba2014-12-01 14:53:08 -08001540 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Chris Lattner5caa3702009-05-08 06:58:22 +00001542 BUILTIN_ROW(__sync_val_compare_and_swap),
1543 BUILTIN_ROW(__sync_bool_compare_and_swap),
1544 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001545 BUILTIN_ROW(__sync_lock_release),
1546 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001547 };
Mike Stump1eb44332009-09-09 15:08:12 +00001548#undef BUILTIN_ROW
1549
Chris Lattner5caa3702009-05-08 06:58:22 +00001550 // Determine the index of the size.
1551 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001552 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001553 case 1: SizeIndex = 0; break;
1554 case 2: SizeIndex = 1; break;
1555 case 4: SizeIndex = 2; break;
1556 case 8: SizeIndex = 3; break;
1557 case 16: SizeIndex = 4; break;
1558 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001559 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1560 << FirstArg->getType() << FirstArg->getSourceRange();
1561 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattner5caa3702009-05-08 06:58:22 +00001564 // Each of these builtins has one pointer argument, followed by some number of
1565 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1566 // that we ignore. Find out which row of BuiltinIndices to read from as well
1567 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001568 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001569 unsigned BuiltinIndex, NumFixed = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08001570 bool WarnAboutSemanticsChange = false;
Chris Lattner5caa3702009-05-08 06:58:22 +00001571 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001572 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001573 case Builtin::BI__sync_fetch_and_add:
1574 case Builtin::BI__sync_fetch_and_add_1:
1575 case Builtin::BI__sync_fetch_and_add_2:
1576 case Builtin::BI__sync_fetch_and_add_4:
1577 case Builtin::BI__sync_fetch_and_add_8:
1578 case Builtin::BI__sync_fetch_and_add_16:
1579 BuiltinIndex = 0;
1580 break;
1581
1582 case Builtin::BI__sync_fetch_and_sub:
1583 case Builtin::BI__sync_fetch_and_sub_1:
1584 case Builtin::BI__sync_fetch_and_sub_2:
1585 case Builtin::BI__sync_fetch_and_sub_4:
1586 case Builtin::BI__sync_fetch_and_sub_8:
1587 case Builtin::BI__sync_fetch_and_sub_16:
1588 BuiltinIndex = 1;
1589 break;
1590
1591 case Builtin::BI__sync_fetch_and_or:
1592 case Builtin::BI__sync_fetch_and_or_1:
1593 case Builtin::BI__sync_fetch_and_or_2:
1594 case Builtin::BI__sync_fetch_and_or_4:
1595 case Builtin::BI__sync_fetch_and_or_8:
1596 case Builtin::BI__sync_fetch_and_or_16:
1597 BuiltinIndex = 2;
1598 break;
1599
1600 case Builtin::BI__sync_fetch_and_and:
1601 case Builtin::BI__sync_fetch_and_and_1:
1602 case Builtin::BI__sync_fetch_and_and_2:
1603 case Builtin::BI__sync_fetch_and_and_4:
1604 case Builtin::BI__sync_fetch_and_and_8:
1605 case Builtin::BI__sync_fetch_and_and_16:
1606 BuiltinIndex = 3;
1607 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Douglas Gregora9766412011-11-28 16:30:08 +00001609 case Builtin::BI__sync_fetch_and_xor:
1610 case Builtin::BI__sync_fetch_and_xor_1:
1611 case Builtin::BI__sync_fetch_and_xor_2:
1612 case Builtin::BI__sync_fetch_and_xor_4:
1613 case Builtin::BI__sync_fetch_and_xor_8:
1614 case Builtin::BI__sync_fetch_and_xor_16:
1615 BuiltinIndex = 4;
1616 break;
1617
Stephen Hines176edba2014-12-01 14:53:08 -08001618 case Builtin::BI__sync_fetch_and_nand:
1619 case Builtin::BI__sync_fetch_and_nand_1:
1620 case Builtin::BI__sync_fetch_and_nand_2:
1621 case Builtin::BI__sync_fetch_and_nand_4:
1622 case Builtin::BI__sync_fetch_and_nand_8:
1623 case Builtin::BI__sync_fetch_and_nand_16:
1624 BuiltinIndex = 5;
1625 WarnAboutSemanticsChange = true;
1626 break;
1627
Douglas Gregora9766412011-11-28 16:30:08 +00001628 case Builtin::BI__sync_add_and_fetch:
1629 case Builtin::BI__sync_add_and_fetch_1:
1630 case Builtin::BI__sync_add_and_fetch_2:
1631 case Builtin::BI__sync_add_and_fetch_4:
1632 case Builtin::BI__sync_add_and_fetch_8:
1633 case Builtin::BI__sync_add_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001634 BuiltinIndex = 6;
Douglas Gregora9766412011-11-28 16:30:08 +00001635 break;
1636
1637 case Builtin::BI__sync_sub_and_fetch:
1638 case Builtin::BI__sync_sub_and_fetch_1:
1639 case Builtin::BI__sync_sub_and_fetch_2:
1640 case Builtin::BI__sync_sub_and_fetch_4:
1641 case Builtin::BI__sync_sub_and_fetch_8:
1642 case Builtin::BI__sync_sub_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001643 BuiltinIndex = 7;
Douglas Gregora9766412011-11-28 16:30:08 +00001644 break;
1645
1646 case Builtin::BI__sync_and_and_fetch:
1647 case Builtin::BI__sync_and_and_fetch_1:
1648 case Builtin::BI__sync_and_and_fetch_2:
1649 case Builtin::BI__sync_and_and_fetch_4:
1650 case Builtin::BI__sync_and_and_fetch_8:
1651 case Builtin::BI__sync_and_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001652 BuiltinIndex = 8;
Douglas Gregora9766412011-11-28 16:30:08 +00001653 break;
1654
1655 case Builtin::BI__sync_or_and_fetch:
1656 case Builtin::BI__sync_or_and_fetch_1:
1657 case Builtin::BI__sync_or_and_fetch_2:
1658 case Builtin::BI__sync_or_and_fetch_4:
1659 case Builtin::BI__sync_or_and_fetch_8:
1660 case Builtin::BI__sync_or_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001661 BuiltinIndex = 9;
Douglas Gregora9766412011-11-28 16:30:08 +00001662 break;
1663
1664 case Builtin::BI__sync_xor_and_fetch:
1665 case Builtin::BI__sync_xor_and_fetch_1:
1666 case Builtin::BI__sync_xor_and_fetch_2:
1667 case Builtin::BI__sync_xor_and_fetch_4:
1668 case Builtin::BI__sync_xor_and_fetch_8:
1669 case Builtin::BI__sync_xor_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001670 BuiltinIndex = 10;
1671 break;
1672
1673 case Builtin::BI__sync_nand_and_fetch:
1674 case Builtin::BI__sync_nand_and_fetch_1:
1675 case Builtin::BI__sync_nand_and_fetch_2:
1676 case Builtin::BI__sync_nand_and_fetch_4:
1677 case Builtin::BI__sync_nand_and_fetch_8:
1678 case Builtin::BI__sync_nand_and_fetch_16:
1679 BuiltinIndex = 11;
1680 WarnAboutSemanticsChange = true;
Douglas Gregora9766412011-11-28 16:30:08 +00001681 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Chris Lattner5caa3702009-05-08 06:58:22 +00001683 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001684 case Builtin::BI__sync_val_compare_and_swap_1:
1685 case Builtin::BI__sync_val_compare_and_swap_2:
1686 case Builtin::BI__sync_val_compare_and_swap_4:
1687 case Builtin::BI__sync_val_compare_and_swap_8:
1688 case Builtin::BI__sync_val_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001689 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +00001690 NumFixed = 2;
1691 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001692
Chris Lattner5caa3702009-05-08 06:58:22 +00001693 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001694 case Builtin::BI__sync_bool_compare_and_swap_1:
1695 case Builtin::BI__sync_bool_compare_and_swap_2:
1696 case Builtin::BI__sync_bool_compare_and_swap_4:
1697 case Builtin::BI__sync_bool_compare_and_swap_8:
1698 case Builtin::BI__sync_bool_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001699 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001700 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001701 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001702 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001703
1704 case Builtin::BI__sync_lock_test_and_set:
1705 case Builtin::BI__sync_lock_test_and_set_1:
1706 case Builtin::BI__sync_lock_test_and_set_2:
1707 case Builtin::BI__sync_lock_test_and_set_4:
1708 case Builtin::BI__sync_lock_test_and_set_8:
1709 case Builtin::BI__sync_lock_test_and_set_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001710 BuiltinIndex = 14;
Douglas Gregora9766412011-11-28 16:30:08 +00001711 break;
1712
Chris Lattner5caa3702009-05-08 06:58:22 +00001713 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001714 case Builtin::BI__sync_lock_release_1:
1715 case Builtin::BI__sync_lock_release_2:
1716 case Builtin::BI__sync_lock_release_4:
1717 case Builtin::BI__sync_lock_release_8:
1718 case Builtin::BI__sync_lock_release_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001719 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +00001720 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001721 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001722 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001723
1724 case Builtin::BI__sync_swap:
1725 case Builtin::BI__sync_swap_1:
1726 case Builtin::BI__sync_swap_2:
1727 case Builtin::BI__sync_swap_4:
1728 case Builtin::BI__sync_swap_8:
1729 case Builtin::BI__sync_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001730 BuiltinIndex = 16;
Douglas Gregora9766412011-11-28 16:30:08 +00001731 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattner5caa3702009-05-08 06:58:22 +00001734 // Now that we know how many fixed arguments we expect, first check that we
1735 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001736 if (TheCall->getNumArgs() < 1+NumFixed) {
1737 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1738 << 0 << 1+NumFixed << TheCall->getNumArgs()
1739 << TheCall->getCallee()->getSourceRange();
1740 return ExprError();
1741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Stephen Hines176edba2014-12-01 14:53:08 -08001743 if (WarnAboutSemanticsChange) {
1744 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1745 << TheCall->getCallee()->getSourceRange();
1746 }
1747
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001748 // Get the decl for the concrete builtin from this, we can tell what the
1749 // concrete integer type we should convert to is.
1750 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1751 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001752 FunctionDecl *NewBuiltinDecl;
1753 if (NewBuiltinID == BuiltinID)
1754 NewBuiltinDecl = FDecl;
1755 else {
1756 // Perform builtin lookup to avoid redeclaring it.
1757 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1758 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1759 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1760 assert(Res.getFoundDecl());
1761 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001762 if (!NewBuiltinDecl)
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001763 return ExprError();
1764 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001765
John McCallf871d0c2010-08-07 06:22:56 +00001766 // The first argument --- the pointer --- has a fixed type; we
1767 // deduce the types of the rest of the arguments accordingly. Walk
1768 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001769 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001770 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Chris Lattner5caa3702009-05-08 06:58:22 +00001772 // GCC does an implicit conversion to the pointer or integer ValType. This
1773 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001774 // Initialize the argument.
1775 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1776 ValType, /*consume*/ false);
1777 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001778 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001779 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Chris Lattner5caa3702009-05-08 06:58:22 +00001781 // Okay, we have something that *can* be converted to the right type. Check
1782 // to see if there is a potentially weird extension going on here. This can
1783 // happen when you do an atomic operation on something like an char* and
1784 // pass in 42. The 42 gets converted to char. This is even more strange
1785 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001786 // FIXME: Do this check.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001787 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001790 ASTContext& Context = this->getASTContext();
1791
1792 // Create a new DeclRefExpr to refer to the new decl.
1793 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1794 Context,
1795 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001796 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001797 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001798 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001799 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001800 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001801 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Chris Lattner5caa3702009-05-08 06:58:22 +00001803 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001804 // FIXME: This loses syntactic information.
1805 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1806 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1807 CK_BuiltinFnToFnPtr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001808 TheCall->setCallee(PromotedCall.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001810 // Change the result type of the call to match the original value type. This
1811 // is arbitrary, but the codegen for these builtins ins design to handle it
1812 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001813 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001814
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001815 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001816}
1817
Chris Lattner69039812009-02-18 06:01:06 +00001818/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001819/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001820/// Note: It might also make sense to do the UTF-16 conversion here (would
1821/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001822bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001823 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001824 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1825
Douglas Gregor5cee1192011-07-27 05:40:30 +00001826 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001827 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1828 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001829 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001832 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001833 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001834 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001835 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001836 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001837 UTF16 *ToPtr = &ToBuf[0];
1838
1839 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1840 &ToPtr, ToPtr + NumBytes,
1841 strictConversion);
1842 // Check for conversion failure.
1843 if (Result != conversionOK)
1844 Diag(Arg->getLocStart(),
1845 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1846 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001847 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001848}
1849
Chris Lattnerc27c6652007-12-20 00:05:45 +00001850/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1851/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001852bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1853 Expr *Fn = TheCall->getCallee();
1854 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001855 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001856 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001857 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1858 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001859 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001860 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001861 return true;
1862 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001863
1864 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001865 return Diag(TheCall->getLocEnd(),
1866 diag::err_typecheck_call_too_few_args_at_least)
1867 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001868 }
1869
John McCall5f8d6042011-08-27 01:09:30 +00001870 // Type-check the first argument normally.
1871 if (checkBuiltinArgument(*this, TheCall, 0))
1872 return true;
1873
Chris Lattnerc27c6652007-12-20 00:05:45 +00001874 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001875 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001876 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001877 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001878 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001879 else if (FunctionDecl *FD = getCurFunctionDecl())
1880 isVariadic = FD->isVariadic();
1881 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001882 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Chris Lattnerc27c6652007-12-20 00:05:45 +00001884 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001885 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1886 return true;
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattner30ce3442007-12-19 23:59:04 +00001889 // Verify that the second argument to the builtin is the last argument of the
1890 // current function or method.
1891 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001892 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Nico Weberb07d4482013-05-24 23:31:57 +00001894 // These are valid if SecondArgIsLastNamedArgument is false after the next
1895 // block.
1896 QualType Type;
1897 SourceLocation ParamLoc;
1898
Anders Carlsson88cf2262008-02-11 04:20:54 +00001899 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1900 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001901 // FIXME: This isn't correct for methods (results in bogus warning).
1902 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001903 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001904 if (CurBlock)
1905 LastArg = *(CurBlock->TheDecl->param_end()-1);
1906 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001907 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001908 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001909 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001910 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001911
1912 Type = PV->getType();
1913 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001914 }
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattner30ce3442007-12-19 23:59:04 +00001917 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001918 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001919 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001920 else if (Type->isReferenceType()) {
1921 Diag(Arg->getLocStart(),
1922 diag::warn_va_start_of_reference_type_is_undefined);
1923 Diag(ParamLoc, diag::note_parameter_type) << Type;
1924 }
1925
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001926 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001927 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001928}
Chris Lattner30ce3442007-12-19 23:59:04 +00001929
Stephen Hines176edba2014-12-01 14:53:08 -08001930bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1931 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1932 // const char *named_addr);
1933
1934 Expr *Func = Call->getCallee();
1935
1936 if (Call->getNumArgs() < 3)
1937 return Diag(Call->getLocEnd(),
1938 diag::err_typecheck_call_too_few_args_at_least)
1939 << 0 /*function call*/ << 3 << Call->getNumArgs();
1940
1941 // Determine whether the current function is variadic or not.
1942 bool IsVariadic;
1943 if (BlockScopeInfo *CurBlock = getCurBlock())
1944 IsVariadic = CurBlock->TheDecl->isVariadic();
1945 else if (FunctionDecl *FD = getCurFunctionDecl())
1946 IsVariadic = FD->isVariadic();
1947 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1948 IsVariadic = MD->isVariadic();
1949 else
1950 llvm_unreachable("unexpected statement type");
1951
1952 if (!IsVariadic) {
1953 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1954 return true;
1955 }
1956
1957 // Type-check the first argument normally.
1958 if (checkBuiltinArgument(*this, Call, 0))
1959 return true;
1960
1961 static const struct {
1962 unsigned ArgNo;
1963 QualType Type;
1964 } ArgumentTypes[] = {
1965 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1966 { 2, Context.getSizeType() },
1967 };
1968
1969 for (const auto &AT : ArgumentTypes) {
1970 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1971 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1972 continue;
1973 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1974 << Arg->getType() << AT.Type << 1 /* different class */
1975 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1976 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1977 }
1978
1979 return false;
1980}
1981
Chris Lattner1b9a0792007-12-20 00:26:33 +00001982/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1983/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001984bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1985 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001986 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001987 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001988 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001989 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001990 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001991 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001992 << SourceRange(TheCall->getArg(2)->getLocStart(),
1993 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001994
John Wiegley429bb272011-04-08 18:41:53 +00001995 ExprResult OrigArg0 = TheCall->getArg(0);
1996 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001997
Chris Lattner1b9a0792007-12-20 00:26:33 +00001998 // Do standard promotions between the two arguments, returning their common
1999 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00002000 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00002001 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2002 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00002003
2004 // Make sure any conversions are pushed back into the call; this is
2005 // type safe since unordered compare builtins are declared as "_Bool
2006 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00002007 TheCall->setArg(0, OrigArg0.get());
2008 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John Wiegley429bb272011-04-08 18:41:53 +00002010 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00002011 return false;
2012
Chris Lattner1b9a0792007-12-20 00:26:33 +00002013 // If the common type isn't a real floating type, then the arguments were
2014 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00002015 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00002016 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002017 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00002018 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2019 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner1b9a0792007-12-20 00:26:33 +00002021 return false;
2022}
2023
Benjamin Kramere771a7a2010-02-15 22:42:31 +00002024/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2025/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002026/// to check everything. We expect the last argument to be a floating point
2027/// value.
2028bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2029 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00002030 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002031 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002032 if (TheCall->getNumArgs() > NumArgs)
2033 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002034 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002035 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002036 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002037 (*(TheCall->arg_end()-1))->getLocEnd());
2038
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002039 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Eli Friedman9ac6f622009-08-31 20:06:00 +00002041 if (OrigArg->isTypeDependent())
2042 return false;
2043
Chris Lattner81368fb2010-05-06 05:50:07 +00002044 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00002045 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00002046 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002047 diag::err_typecheck_call_invalid_unary_fp)
2048 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattner81368fb2010-05-06 05:50:07 +00002050 // If this is an implicit conversion from float -> double, remove it.
2051 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2052 Expr *CastArg = Cast->getSubExpr();
2053 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2054 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2055 "promotion from float to double is the only expected cast here");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002056 Cast->setSubExpr(nullptr);
Chris Lattner81368fb2010-05-06 05:50:07 +00002057 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00002058 }
2059 }
2060
Eli Friedman9ac6f622009-08-31 20:06:00 +00002061 return false;
2062}
2063
Eli Friedmand38617c2008-05-14 19:38:39 +00002064/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2065// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00002066ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002067 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002068 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00002069 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00002070 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2071 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002072
Nate Begeman37b6a572010-06-08 00:16:34 +00002073 // Determine which of the following types of shufflevector we're checking:
2074 // 1) unary, vector mask: (lhs, mask)
2075 // 2) binary, vector mask: (lhs, rhs, mask)
2076 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2077 QualType resType = TheCall->getArg(0)->getType();
2078 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00002079
Douglas Gregorcde01732009-05-19 22:10:17 +00002080 if (!TheCall->getArg(0)->isTypeDependent() &&
2081 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002082 QualType LHSType = TheCall->getArg(0)->getType();
2083 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00002084
Craig Topperbbe759c2013-07-29 06:47:04 +00002085 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2086 return ExprError(Diag(TheCall->getLocStart(),
2087 diag::err_shufflevector_non_vector)
2088 << SourceRange(TheCall->getArg(0)->getLocStart(),
2089 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002090
Nate Begeman37b6a572010-06-08 00:16:34 +00002091 numElements = LHSType->getAs<VectorType>()->getNumElements();
2092 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Nate Begeman37b6a572010-06-08 00:16:34 +00002094 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2095 // with mask. If so, verify that RHS is an integer vector type with the
2096 // same number of elts as lhs.
2097 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00002098 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00002099 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00002100 return ExprError(Diag(TheCall->getLocStart(),
2101 diag::err_shufflevector_incompatible_vector)
2102 << SourceRange(TheCall->getArg(1)->getLocStart(),
2103 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002104 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00002105 return ExprError(Diag(TheCall->getLocStart(),
2106 diag::err_shufflevector_incompatible_vector)
2107 << SourceRange(TheCall->getArg(0)->getLocStart(),
2108 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00002109 } else if (numElements != numResElements) {
2110 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00002111 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002112 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00002113 }
Eli Friedmand38617c2008-05-14 19:38:39 +00002114 }
2115
2116 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00002117 if (TheCall->getArg(i)->isTypeDependent() ||
2118 TheCall->getArg(i)->isValueDependent())
2119 continue;
2120
Nate Begeman37b6a572010-06-08 00:16:34 +00002121 llvm::APSInt Result(32);
2122 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2123 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002124 diag::err_shufflevector_nonconstant_argument)
2125 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002126
Craig Topper6f4f8082013-08-03 17:40:38 +00002127 // Allow -1 which will be translated to undef in the IR.
2128 if (Result.isSigned() && Result.isAllOnesValue())
2129 continue;
2130
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002131 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002132 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002133 diag::err_shufflevector_argument_too_large)
2134 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002135 }
2136
Chris Lattner5f9e2722011-07-23 10:55:15 +00002137 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00002138
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002139 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00002140 exprs.push_back(TheCall->getArg(i));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002141 TheCall->setArg(i, nullptr);
Eli Friedmand38617c2008-05-14 19:38:39 +00002142 }
2143
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002144 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2145 TheCall->getCallee()->getLocStart(),
2146 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +00002147}
Chris Lattner30ce3442007-12-19 23:59:04 +00002148
Hal Finkel414a1bd2013-09-18 03:29:45 +00002149/// SemaConvertVectorExpr - Handle __builtin_convertvector
2150ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2151 SourceLocation BuiltinLoc,
2152 SourceLocation RParenLoc) {
2153 ExprValueKind VK = VK_RValue;
2154 ExprObjectKind OK = OK_Ordinary;
2155 QualType DstTy = TInfo->getType();
2156 QualType SrcTy = E->getType();
2157
2158 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2159 return ExprError(Diag(BuiltinLoc,
2160 diag::err_convertvector_non_vector)
2161 << E->getSourceRange());
2162 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2163 return ExprError(Diag(BuiltinLoc,
2164 diag::err_convertvector_non_vector_type));
2165
2166 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2167 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2168 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2169 if (SrcElts != DstElts)
2170 return ExprError(Diag(BuiltinLoc,
2171 diag::err_convertvector_incompatible_vector)
2172 << E->getSourceRange());
2173 }
2174
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002175 return new (Context)
2176 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkel414a1bd2013-09-18 03:29:45 +00002177}
2178
Daniel Dunbar4493f792008-07-21 22:59:13 +00002179/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2180// This is declared to take (const void*, ...) and can take two
2181// optional constant int args.
2182bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002183 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002184
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002185 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00002186 return Diag(TheCall->getLocEnd(),
2187 diag::err_typecheck_call_too_many_args_at_most)
2188 << 0 /*function call*/ << 3 << NumArgs
2189 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002190
2191 // Argument 0 is checked for us and the remaining arguments must be
2192 // constant integers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002193 for (unsigned i = 1; i != NumArgs; ++i)
2194 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher691ebc32010-04-17 02:26:23 +00002195 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Stephen Hines651f13c2014-04-23 16:59:28 -07002197 return false;
2198}
2199
Stephen Hines176edba2014-12-01 14:53:08 -08002200/// SemaBuiltinAssume - Handle __assume (MS Extension).
2201// __assume does not evaluate its arguments, and should warn if its argument
2202// has side effects.
2203bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2204 Expr *Arg = TheCall->getArg(0);
2205 if (Arg->isInstantiationDependent()) return false;
2206
2207 if (Arg->HasSideEffects(Context))
2208 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2209 << Arg->getSourceRange()
2210 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2211
2212 return false;
2213}
2214
2215/// Handle __builtin_assume_aligned. This is declared
2216/// as (const void*, size_t, ...) and can take one optional constant int arg.
2217bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2218 unsigned NumArgs = TheCall->getNumArgs();
2219
2220 if (NumArgs > 3)
2221 return Diag(TheCall->getLocEnd(),
2222 diag::err_typecheck_call_too_many_args_at_most)
2223 << 0 /*function call*/ << 3 << NumArgs
2224 << TheCall->getSourceRange();
2225
2226 // The alignment must be a constant integer.
2227 Expr *Arg = TheCall->getArg(1);
2228
2229 // We can't check the value of a dependent argument.
2230 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2231 llvm::APSInt Result;
2232 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2233 return true;
2234
2235 if (!Result.isPowerOf2())
2236 return Diag(TheCall->getLocStart(),
2237 diag::err_alignment_not_power_of_two)
2238 << Arg->getSourceRange();
2239 }
2240
2241 if (NumArgs > 2) {
2242 ExprResult Arg(TheCall->getArg(2));
2243 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2244 Context.getSizeType(), false);
2245 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2246 if (Arg.isInvalid()) return true;
2247 TheCall->setArg(2, Arg.get());
2248 }
2249
2250 return false;
2251}
2252
Eric Christopher691ebc32010-04-17 02:26:23 +00002253/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2254/// TheCall is a constant expression.
2255bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2256 llvm::APSInt &Result) {
2257 Expr *Arg = TheCall->getArg(ArgNum);
2258 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2259 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2260
2261 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2262
2263 if (!Arg->isIntegerConstantExpr(Result, Context))
2264 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00002265 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00002266
Chris Lattner21fb98e2009-09-23 06:06:36 +00002267 return false;
2268}
2269
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002270/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2271/// TheCall is a constant expression in the range [Low, High].
2272bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2273 int Low, int High) {
Eric Christopher691ebc32010-04-17 02:26:23 +00002274 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00002275
2276 // We can't check the value of a dependent argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002277 Expr *Arg = TheCall->getArg(ArgNum);
2278 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor592a4232012-06-29 01:05:22 +00002279 return false;
2280
Eric Christopher691ebc32010-04-17 02:26:23 +00002281 // Check constant-ness first.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002282 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher691ebc32010-04-17 02:26:23 +00002283 return true;
2284
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002285 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002286 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002287 << Low << High << Arg->getSourceRange();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002288
2289 return false;
2290}
2291
Eli Friedman586d6a82009-05-03 06:04:26 +00002292/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00002293/// This checks that val is a constant 1.
2294bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2295 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00002296 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00002297
Eric Christopher691ebc32010-04-17 02:26:23 +00002298 // TODO: This is less than ideal. Overload this to take a value.
2299 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2300 return true;
2301
2302 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00002303 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2304 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2305
2306 return false;
2307}
2308
Richard Smith0e218972013-08-05 18:49:43 +00002309namespace {
2310enum StringLiteralCheckType {
2311 SLCT_NotALiteral,
2312 SLCT_UncheckedLiteral,
2313 SLCT_CheckedLiteral
2314};
2315}
2316
Richard Smith831421f2012-06-25 20:30:08 +00002317// Determine if an expression is a string literal or constant string.
2318// If this function returns false on the arguments to a function expecting a
2319// format string, we will usually need to emit a warning.
2320// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00002321static StringLiteralCheckType
2322checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2323 bool HasVAListArg, unsigned format_idx,
2324 unsigned firstDataArg, Sema::FormatStringType Type,
2325 Sema::VariadicCallType CallType, bool InFunctionCall,
2326 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002327 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00002328 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00002329 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002330
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002331 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002332
Richard Smith0e218972013-08-05 18:49:43 +00002333 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00002334 // Technically -Wformat-nonliteral does not warn about this case.
2335 // The behavior of printf and friends in this case is implementation
2336 // dependent. Ideally if the format string cannot be null then
2337 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00002338 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002339
Ted Kremenekd30ef872009-01-12 23:09:09 +00002340 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002341 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002342 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00002343 // The expression is a literal if both sub-expressions were, and it was
2344 // completely checked only if both sub-expressions were checked.
2345 const AbstractConditionalOperator *C =
2346 cast<AbstractConditionalOperator>(E);
2347 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002348 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002349 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002350 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002351 if (Left == SLCT_NotALiteral)
2352 return SLCT_NotALiteral;
2353 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002354 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002355 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002356 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002357 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002358 }
2359
2360 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002361 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2362 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002363 }
2364
John McCall56ca35d2011-02-17 10:25:35 +00002365 case Stmt::OpaqueValueExprClass:
2366 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2367 E = src;
2368 goto tryAgain;
2369 }
Richard Smith831421f2012-06-25 20:30:08 +00002370 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002371
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002372 case Stmt::PredefinedExprClass:
2373 // While __func__, etc., are technically not string literals, they
2374 // cannot contain format specifiers and thus are not a security
2375 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002376 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002377
Ted Kremenek082d9362009-03-20 21:35:28 +00002378 case Stmt::DeclRefExprClass: {
2379 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Ted Kremenek082d9362009-03-20 21:35:28 +00002381 // As an exception, do not flag errors for variables binding to
2382 // const string literals.
2383 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2384 bool isConstant = false;
2385 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002386
Richard Smith0e218972013-08-05 18:49:43 +00002387 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2388 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002389 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002390 isConstant = T.isConstant(S.Context) &&
2391 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002392 } else if (T->isObjCObjectPointerType()) {
2393 // In ObjC, there is usually no "const ObjectPointer" type,
2394 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002395 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Ted Kremenek082d9362009-03-20 21:35:28 +00002398 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002399 if (const Expr *Init = VD->getAnyInitializer()) {
2400 // Look through initializers like const char c[] = { "foo" }
2401 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2402 if (InitList->isStringLiteralInit())
2403 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2404 }
Richard Smith0e218972013-08-05 18:49:43 +00002405 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002406 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002407 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002408 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002409 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002410 }
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Anders Carlssond966a552009-06-28 19:55:58 +00002412 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2413 // special check to see if the format string is a function parameter
2414 // of the function calling the printf function. If the function
2415 // has an attribute indicating it is a printf-like function, then we
2416 // should suppress warnings concerning non-literals being used in a call
2417 // to a vprintf function. For example:
2418 //
2419 // void
2420 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2421 // va_list ap;
2422 // va_start(ap, fmt);
2423 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2424 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002425 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002426 if (HasVAListArg) {
2427 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2428 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2429 int PVIndex = PV->getFunctionScopeIndex() + 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002430 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002431 // adjust for implicit parameter
2432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2433 if (MD->isInstance())
2434 ++PVIndex;
2435 // We also check if the formats are compatible.
2436 // We can't pass a 'scanf' string to a 'printf' function.
2437 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002438 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002439 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002440 }
2441 }
2442 }
2443 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002444 }
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Richard Smith831421f2012-06-25 20:30:08 +00002446 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002447 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002448
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002449 case Stmt::CallExprClass:
2450 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002451 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002452 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2453 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2454 unsigned ArgIndex = FA->getFormatIdx();
2455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2456 if (MD->isInstance())
2457 --ArgIndex;
2458 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Richard Smith0e218972013-08-05 18:49:43 +00002460 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002461 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002462 Type, CallType, InFunctionCall,
2463 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002464 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2465 unsigned BuiltinID = FD->getBuiltinID();
2466 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2467 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2468 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002469 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002470 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002471 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002472 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002473 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002474 }
2475 }
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Richard Smith831421f2012-06-25 20:30:08 +00002477 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002478 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002479 case Stmt::ObjCStringLiteralClass:
2480 case Stmt::StringLiteralClass: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002481 const StringLiteral *StrE = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Ted Kremenek082d9362009-03-20 21:35:28 +00002483 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002484 StrE = ObjCFExpr->getString();
2485 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002486 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Ted Kremenekd30ef872009-01-12 23:09:09 +00002488 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002489 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2490 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002491 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002492 }
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Richard Smith831421f2012-06-25 20:30:08 +00002494 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002495 }
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Ted Kremenek082d9362009-03-20 21:35:28 +00002497 default:
Richard Smith831421f2012-06-25 20:30:08 +00002498 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002499 }
2500}
2501
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002502Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002503 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002504 .Case("scanf", FST_Scanf)
2505 .Cases("printf", "printf0", FST_Printf)
2506 .Cases("NSString", "CFString", FST_NSString)
2507 .Case("strftime", FST_Strftime)
2508 .Case("strfmon", FST_Strfmon)
2509 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2510 .Default(FST_Unknown);
2511}
2512
Jordan Roseddcfbc92012-07-19 18:10:23 +00002513/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002514/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002515/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002516bool Sema::CheckFormatArguments(const FormatAttr *Format,
2517 ArrayRef<const Expr *> Args,
2518 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002519 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002520 SourceLocation Loc, SourceRange Range,
2521 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002522 FormatStringInfo FSI;
2523 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002524 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002525 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002526 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002527 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002528}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002529
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002530bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002531 bool HasVAListArg, unsigned format_idx,
2532 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002533 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002534 SourceLocation Loc, SourceRange Range,
2535 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002536 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002537 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002538 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002539 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002540 }
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002542 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Chris Lattner59907c42007-08-10 20:18:51 +00002544 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002545 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002546 // Dynamically generated format strings are difficult to
2547 // automatically vet at compile time. Requiring that format strings
2548 // are string literals: (1) permits the checking of format strings by
2549 // the compiler and thereby (2) can practically remove the source of
2550 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002551
Mike Stump1eb44332009-09-09 15:08:12 +00002552 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002553 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002554 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002555 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002556 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002557 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2558 format_idx, firstDataArg, Type, CallType,
2559 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002560 if (CT != SLCT_NotALiteral)
2561 // Literal format string found, check done!
2562 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002563
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002564 // Strftime is particular as it always uses a single 'time' argument,
2565 // so it is safe to pass a non-literal string.
2566 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002567 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002568
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002569 // Do not emit diag when the string param is a macro expansion and the
2570 // format is either NSString or CFString. This is a hack to prevent
2571 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2572 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002573 if (Type == FST_NSString &&
2574 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002575 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002576
Chris Lattner655f1412009-04-29 04:59:47 +00002577 // If there are no arguments specified, warn with -Wformat-security, otherwise
2578 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002579 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002580 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002581 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002582 << OrigFormatExpr->getSourceRange();
2583 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002584 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002585 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002586 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002587 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002588}
Ted Kremenek71895b92007-08-14 17:39:48 +00002589
Ted Kremeneke0e53132010-01-28 23:39:18 +00002590namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002591class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2592protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002593 Sema &S;
2594 const StringLiteral *FExpr;
2595 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002596 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002597 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002598 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002599 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002600 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002601 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002602 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002603 bool usesPositionalArgs;
2604 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002605 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002606 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002607 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002608public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002609 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002610 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002611 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002612 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002613 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002614 Sema::VariadicCallType callType,
2615 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002616 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002617 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2618 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002619 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002620 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002621 inFunctionCall(inFunctionCall), CallType(callType),
2622 CheckedVarArgs(CheckedVarArgs) {
2623 CoveredArgs.resize(numDataArgs);
2624 CoveredArgs.reset();
2625 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002626
Ted Kremenek07d161f2010-01-29 01:50:07 +00002627 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002628
Ted Kremenek826a3452010-07-16 02:11:22 +00002629 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002630 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002631
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002632 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002633 const analyze_format_string::FormatSpecifier &FS,
2634 const analyze_format_string::ConversionSpecifier &CS,
2635 const char *startSpecifier, unsigned specifierLen,
2636 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002637
Hans Wennborg76517422012-02-22 10:17:01 +00002638 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002639 const analyze_format_string::FormatSpecifier &FS,
2640 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002641
2642 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002643 const analyze_format_string::ConversionSpecifier &CS,
2644 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002645
Stephen Hines651f13c2014-04-23 16:59:28 -07002646 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002647
Stephen Hines651f13c2014-04-23 16:59:28 -07002648 void HandleInvalidPosition(const char *startSpecifier,
2649 unsigned specifierLen,
2650 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002651
Stephen Hines651f13c2014-04-23 16:59:28 -07002652 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002653
Stephen Hines651f13c2014-04-23 16:59:28 -07002654 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002655
Richard Trieu55733de2011-10-28 00:41:25 +00002656 template <typename Range>
2657 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2658 const Expr *ArgumentExpr,
2659 PartialDiagnostic PDiag,
2660 SourceLocation StringLoc,
2661 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002662 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002663
Ted Kremenek826a3452010-07-16 02:11:22 +00002664protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002665 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2666 const char *startSpec,
2667 unsigned specifierLen,
2668 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002669
2670 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2671 const char *startSpec,
2672 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002673
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002674 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002675 CharSourceRange getSpecifierRange(const char *startSpecifier,
2676 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002677 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002678
Ted Kremenek0d277352010-01-29 01:06:55 +00002679 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002680
2681 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2682 const analyze_format_string::ConversionSpecifier &CS,
2683 const char *startSpecifier, unsigned specifierLen,
2684 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002685
2686 template <typename Range>
2687 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2688 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002689 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002690};
2691}
2692
Ted Kremenek826a3452010-07-16 02:11:22 +00002693SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002694 return OrigFormatExpr->getSourceRange();
2695}
2696
Ted Kremenek826a3452010-07-16 02:11:22 +00002697CharSourceRange CheckFormatHandler::
2698getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002699 SourceLocation Start = getLocationOfByte(startSpecifier);
2700 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2701
2702 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002703 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002704
2705 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002706}
2707
Ted Kremenek826a3452010-07-16 02:11:22 +00002708SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002709 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002710}
2711
Ted Kremenek826a3452010-07-16 02:11:22 +00002712void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2713 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002714 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2715 getLocationOfByte(startSpecifier),
2716 /*IsStringLocation*/true,
2717 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002718}
2719
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002720void CheckFormatHandler::HandleInvalidLengthModifier(
2721 const analyze_format_string::FormatSpecifier &FS,
2722 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002723 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002724 using namespace analyze_format_string;
2725
2726 const LengthModifier &LM = FS.getLengthModifier();
2727 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2728
2729 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002730 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002731 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002732 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002733 getLocationOfByte(LM.getStart()),
2734 /*IsStringLocation*/true,
2735 getSpecifierRange(startSpecifier, specifierLen));
2736
2737 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2738 << FixedLM->toString()
2739 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2740
2741 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002742 FixItHint Hint;
2743 if (DiagID == diag::warn_format_nonsensical_length)
2744 Hint = FixItHint::CreateRemoval(LMRange);
2745
2746 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002747 getLocationOfByte(LM.getStart()),
2748 /*IsStringLocation*/true,
2749 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002750 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002751 }
2752}
2753
Hans Wennborg76517422012-02-22 10:17:01 +00002754void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002755 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002756 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002757 using namespace analyze_format_string;
2758
2759 const LengthModifier &LM = FS.getLengthModifier();
2760 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2761
2762 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002763 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002764 if (FixedLM) {
2765 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2766 << LM.toString() << 0,
2767 getLocationOfByte(LM.getStart()),
2768 /*IsStringLocation*/true,
2769 getSpecifierRange(startSpecifier, specifierLen));
2770
2771 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2772 << FixedLM->toString()
2773 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2774
2775 } else {
2776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2777 << LM.toString() << 0,
2778 getLocationOfByte(LM.getStart()),
2779 /*IsStringLocation*/true,
2780 getSpecifierRange(startSpecifier, specifierLen));
2781 }
Hans Wennborg76517422012-02-22 10:17:01 +00002782}
2783
2784void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2785 const analyze_format_string::ConversionSpecifier &CS,
2786 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002787 using namespace analyze_format_string;
2788
2789 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002790 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002791 if (FixedCS) {
2792 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2793 << CS.toString() << /*conversion specifier*/1,
2794 getLocationOfByte(CS.getStart()),
2795 /*IsStringLocation*/true,
2796 getSpecifierRange(startSpecifier, specifierLen));
2797
2798 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2799 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2800 << FixedCS->toString()
2801 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2802 } else {
2803 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2804 << CS.toString() << /*conversion specifier*/1,
2805 getLocationOfByte(CS.getStart()),
2806 /*IsStringLocation*/true,
2807 getSpecifierRange(startSpecifier, specifierLen));
2808 }
Hans Wennborg76517422012-02-22 10:17:01 +00002809}
2810
Hans Wennborgf8562642012-03-09 10:10:54 +00002811void CheckFormatHandler::HandlePosition(const char *startPos,
2812 unsigned posLen) {
2813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2814 getLocationOfByte(startPos),
2815 /*IsStringLocation*/true,
2816 getSpecifierRange(startPos, posLen));
2817}
2818
Ted Kremenekefaff192010-02-27 01:41:03 +00002819void
Ted Kremenek826a3452010-07-16 02:11:22 +00002820CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2821 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2823 << (unsigned) p,
2824 getLocationOfByte(startPos), /*IsStringLocation*/true,
2825 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002826}
2827
Ted Kremenek826a3452010-07-16 02:11:22 +00002828void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002829 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2831 getLocationOfByte(startPos),
2832 /*IsStringLocation*/true,
2833 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002834}
2835
Ted Kremenek826a3452010-07-16 02:11:22 +00002836void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002837 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002838 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002839 EmitFormatDiagnostic(
2840 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2841 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2842 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002843 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002844}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002845
Jordan Rose48716662012-07-19 18:10:08 +00002846// Note that this may return NULL if there was an error parsing or building
2847// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002848const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002849 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002850}
2851
2852void CheckFormatHandler::DoneProcessing() {
2853 // Does the number of data arguments exceed the number of
2854 // format conversions in the format string?
2855 if (!HasVAListArg) {
2856 // Find any arguments that weren't covered.
2857 CoveredArgs.flip();
2858 signed notCoveredArg = CoveredArgs.find_first();
2859 if (notCoveredArg >= 0) {
2860 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002861 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2862 SourceLocation Loc = E->getLocStart();
2863 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2865 Loc, /*IsStringLocation*/false,
2866 getFormatStringRange());
2867 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002868 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002869 }
2870 }
2871}
2872
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002873bool
2874CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2875 SourceLocation Loc,
2876 const char *startSpec,
2877 unsigned specifierLen,
2878 const char *csStart,
2879 unsigned csLen) {
2880
2881 bool keepGoing = true;
2882 if (argIndex < NumDataArgs) {
2883 // Consider the argument coverered, even though the specifier doesn't
2884 // make sense.
2885 CoveredArgs.set(argIndex);
2886 }
2887 else {
2888 // If argIndex exceeds the number of data arguments we
2889 // don't issue a warning because that is just a cascade of warnings (and
2890 // they may have intended '%%' anyway). We don't want to continue processing
2891 // the format string after this point, however, as we will like just get
2892 // gibberish when trying to match arguments.
2893 keepGoing = false;
2894 }
2895
Richard Trieu55733de2011-10-28 00:41:25 +00002896 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2897 << StringRef(csStart, csLen),
2898 Loc, /*IsStringLocation*/true,
2899 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002900
2901 return keepGoing;
2902}
2903
Richard Trieu55733de2011-10-28 00:41:25 +00002904void
2905CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2906 const char *startSpec,
2907 unsigned specifierLen) {
2908 EmitFormatDiagnostic(
2909 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2910 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2911}
2912
Ted Kremenek666a1972010-07-26 19:45:42 +00002913bool
2914CheckFormatHandler::CheckNumArgs(
2915 const analyze_format_string::FormatSpecifier &FS,
2916 const analyze_format_string::ConversionSpecifier &CS,
2917 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2918
2919 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002920 PartialDiagnostic PDiag = FS.usesPositionalArg()
2921 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2922 << (argIndex+1) << NumDataArgs)
2923 : S.PDiag(diag::warn_printf_insufficient_data_args);
2924 EmitFormatDiagnostic(
2925 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2926 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002927 return false;
2928 }
2929 return true;
2930}
2931
Richard Trieu55733de2011-10-28 00:41:25 +00002932template<typename Range>
2933void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2934 SourceLocation Loc,
2935 bool IsStringLocation,
2936 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002937 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002938 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002939 Loc, IsStringLocation, StringRange, FixIt);
2940}
2941
2942/// \brief If the format string is not within the funcion call, emit a note
2943/// so that the function call and string are in diagnostic messages.
2944///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002945/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002946/// call and only one diagnostic message will be produced. Otherwise, an
2947/// extra note will be emitted pointing to location of the format string.
2948///
2949/// \param ArgumentExpr the expression that is passed as the format string
2950/// argument in the function call. Used for getting locations when two
2951/// diagnostics are emitted.
2952///
2953/// \param PDiag the callee should already have provided any strings for the
2954/// diagnostic message. This function only adds locations and fixits
2955/// to diagnostics.
2956///
2957/// \param Loc primary location for diagnostic. If two diagnostics are
2958/// required, one will be at Loc and a new SourceLocation will be created for
2959/// the other one.
2960///
2961/// \param IsStringLocation if true, Loc points to the format string should be
2962/// used for the note. Otherwise, Loc points to the argument list and will
2963/// be used with PDiag.
2964///
2965/// \param StringRange some or all of the string to highlight. This is
2966/// templated so it can accept either a CharSourceRange or a SourceRange.
2967///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002968/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002969template<typename Range>
2970void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2971 const Expr *ArgumentExpr,
2972 PartialDiagnostic PDiag,
2973 SourceLocation Loc,
2974 bool IsStringLocation,
2975 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002976 ArrayRef<FixItHint> FixIt) {
2977 if (InFunctionCall) {
2978 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2979 D << StringRange;
2980 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2981 I != E; ++I) {
2982 D << *I;
2983 }
2984 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002985 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2986 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002987
2988 const Sema::SemaDiagnosticBuilder &Note =
2989 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2990 diag::note_format_string_defined);
2991
2992 Note << StringRange;
2993 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2994 I != E; ++I) {
2995 Note << *I;
2996 }
Richard Trieu55733de2011-10-28 00:41:25 +00002997 }
2998}
2999
Ted Kremenek826a3452010-07-16 02:11:22 +00003000//===--- CHECK: Printf format string checking ------------------------------===//
3001
3002namespace {
3003class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00003004 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00003005public:
3006 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3007 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003008 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00003009 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003010 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003011 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003012 Sema::VariadicCallType CallType,
3013 llvm::SmallBitVector &CheckedVarArgs)
3014 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3015 numDataArgs, beg, hasVAListArg, Args,
3016 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3017 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003018 {}
3019
Stephen Hines651f13c2014-04-23 16:59:28 -07003020
Ted Kremenek826a3452010-07-16 02:11:22 +00003021 bool HandleInvalidPrintfConversionSpecifier(
3022 const analyze_printf::PrintfSpecifier &FS,
3023 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003024 unsigned specifierLen) override;
3025
Ted Kremenek826a3452010-07-16 02:11:22 +00003026 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3027 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003028 unsigned specifierLen) override;
Richard Smith831421f2012-06-25 20:30:08 +00003029 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3030 const char *StartSpecifier,
3031 unsigned SpecifierLen,
3032 const Expr *E);
3033
Ted Kremenek826a3452010-07-16 02:11:22 +00003034 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3035 const char *startSpecifier, unsigned specifierLen);
3036 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3037 const analyze_printf::OptionalAmount &Amt,
3038 unsigned type,
3039 const char *startSpecifier, unsigned specifierLen);
3040 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3041 const analyze_printf::OptionalFlag &flag,
3042 const char *startSpecifier, unsigned specifierLen);
3043 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3044 const analyze_printf::OptionalFlag &ignoredFlag,
3045 const analyze_printf::OptionalFlag &flag,
3046 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00003047 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07003048 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00003049
Ted Kremenek826a3452010-07-16 02:11:22 +00003050};
3051}
3052
3053bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3054 const analyze_printf::PrintfSpecifier &FS,
3055 const char *startSpecifier,
3056 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003057 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003058 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003059
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003060 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3061 getLocationOfByte(CS.getStart()),
3062 startSpecifier, specifierLen,
3063 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00003064}
3065
Ted Kremenek826a3452010-07-16 02:11:22 +00003066bool CheckPrintfHandler::HandleAmount(
3067 const analyze_format_string::OptionalAmount &Amt,
3068 unsigned k, const char *startSpecifier,
3069 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003070
3071 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003072 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003073 unsigned argIndex = Amt.getArgIndex();
3074 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00003075 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3076 << k,
3077 getLocationOfByte(Amt.getStart()),
3078 /*IsStringLocation*/true,
3079 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003080 // Don't do any more checking. We will just emit
3081 // spurious errors.
3082 return false;
3083 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003084
Ted Kremenek0d277352010-01-29 01:06:55 +00003085 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00003086 // Although not in conformance with C99, we also allow the argument to be
3087 // an 'unsigned int' as that is a reasonably safe case. GCC also
3088 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003089 CoveredArgs.set(argIndex);
3090 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003091 if (!Arg)
3092 return false;
3093
Ted Kremenek0d277352010-01-29 01:06:55 +00003094 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003095
Hans Wennborgf3749f42012-08-07 08:11:26 +00003096 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3097 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003098
Hans Wennborgf3749f42012-08-07 08:11:26 +00003099 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00003100 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00003101 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00003102 << T << Arg->getSourceRange(),
3103 getLocationOfByte(Amt.getStart()),
3104 /*IsStringLocation*/true,
3105 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003106 // Don't do any more checking. We will just emit
3107 // spurious errors.
3108 return false;
3109 }
3110 }
3111 }
3112 return true;
3113}
Ted Kremenek0d277352010-01-29 01:06:55 +00003114
Tom Caree4ee9662010-06-17 19:00:27 +00003115void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00003116 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003117 const analyze_printf::OptionalAmount &Amt,
3118 unsigned type,
3119 const char *startSpecifier,
3120 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003121 const analyze_printf::PrintfConversionSpecifier &CS =
3122 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00003123
Richard Trieu55733de2011-10-28 00:41:25 +00003124 FixItHint fixit =
3125 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3126 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3127 Amt.getConstantLength()))
3128 : FixItHint();
3129
3130 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3131 << type << CS.toString(),
3132 getLocationOfByte(Amt.getStart()),
3133 /*IsStringLocation*/true,
3134 getSpecifierRange(startSpecifier, specifierLen),
3135 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00003136}
3137
Ted Kremenek826a3452010-07-16 02:11:22 +00003138void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003139 const analyze_printf::OptionalFlag &flag,
3140 const char *startSpecifier,
3141 unsigned specifierLen) {
3142 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003143 const analyze_printf::PrintfConversionSpecifier &CS =
3144 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00003145 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3146 << flag.toString() << CS.toString(),
3147 getLocationOfByte(flag.getPosition()),
3148 /*IsStringLocation*/true,
3149 getSpecifierRange(startSpecifier, specifierLen),
3150 FixItHint::CreateRemoval(
3151 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003152}
3153
3154void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00003155 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003156 const analyze_printf::OptionalFlag &ignoredFlag,
3157 const analyze_printf::OptionalFlag &flag,
3158 const char *startSpecifier,
3159 unsigned specifierLen) {
3160 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00003161 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3162 << ignoredFlag.toString() << flag.toString(),
3163 getLocationOfByte(ignoredFlag.getPosition()),
3164 /*IsStringLocation*/true,
3165 getSpecifierRange(startSpecifier, specifierLen),
3166 FixItHint::CreateRemoval(
3167 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003168}
3169
Richard Smith831421f2012-06-25 20:30:08 +00003170// Determines if the specified is a C++ class or struct containing
3171// a member with the specified name and kind (e.g. a CXXMethodDecl named
3172// "c_str()").
3173template<typename MemberKind>
3174static llvm::SmallPtrSet<MemberKind*, 1>
3175CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3176 const RecordType *RT = Ty->getAs<RecordType>();
3177 llvm::SmallPtrSet<MemberKind*, 1> Results;
3178
3179 if (!RT)
3180 return Results;
3181 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07003182 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00003183 return Results;
3184
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003185 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith831421f2012-06-25 20:30:08 +00003186 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07003187 R.suppressDiagnostics();
Richard Smith831421f2012-06-25 20:30:08 +00003188
3189 // We just need to include all members of the right kind turned up by the
3190 // filter, at this point.
3191 if (S.LookupQualifiedName(R, RT->getDecl()))
3192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3193 NamedDecl *decl = (*I)->getUnderlyingDecl();
3194 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3195 Results.insert(FK);
3196 }
3197 return Results;
3198}
3199
Stephen Hines651f13c2014-04-23 16:59:28 -07003200/// Check if we could call '.c_str()' on an object.
3201///
3202/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3203/// allow the call, or if it would be ambiguous).
3204bool Sema::hasCStrMethod(const Expr *E) {
3205 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3206 MethodSet Results =
3207 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3208 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3209 MI != ME; ++MI)
3210 if ((*MI)->getMinRequiredArguments() == 0)
3211 return true;
3212 return false;
3213}
3214
Richard Smith831421f2012-06-25 20:30:08 +00003215// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00003216// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00003217// Returns true when a c_str() conversion method is found.
3218bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07003219 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-06-25 20:30:08 +00003220 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3221
3222 MethodSet Results =
3223 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3224
3225 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3226 MI != ME; ++MI) {
3227 const CXXMethodDecl *Method = *MI;
Stephen Hines651f13c2014-04-23 16:59:28 -07003228 if (Method->getMinRequiredArguments() == 0 &&
3229 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00003230 // FIXME: Suggest parens if the expression needs them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003231 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith831421f2012-06-25 20:30:08 +00003232 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3233 << "c_str()"
3234 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3235 return true;
3236 }
3237 }
3238
3239 return false;
3240}
3241
Ted Kremeneke0e53132010-01-28 23:39:18 +00003242bool
Ted Kremenek826a3452010-07-16 02:11:22 +00003243CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00003244 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00003245 const char *startSpecifier,
3246 unsigned specifierLen) {
3247
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003248 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00003249 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003250 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00003251
Ted Kremenekbaa40062010-07-19 22:01:06 +00003252 if (FS.consumesDataArgument()) {
3253 if (atFirstArg) {
3254 atFirstArg = false;
3255 usesPositionalArgs = FS.usesPositionalArg();
3256 }
3257 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003258 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3259 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003260 return false;
3261 }
Ted Kremenek0d277352010-01-29 01:06:55 +00003262 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003263
Ted Kremenekefaff192010-02-27 01:41:03 +00003264 // First check if the field width, precision, and conversion specifier
3265 // have matching data arguments.
3266 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3267 startSpecifier, specifierLen)) {
3268 return false;
3269 }
3270
3271 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3272 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003273 return false;
3274 }
3275
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003276 if (!CS.consumesDataArgument()) {
3277 // FIXME: Technically specifying a precision or field width here
3278 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003279 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003280 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003281
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003282 // Consume the argument.
3283 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00003284 if (argIndex < NumDataArgs) {
3285 // The check to see if the argIndex is valid will come later.
3286 // We set the bit here because we may exit early from this
3287 // function if we encounter some other error.
3288 CoveredArgs.set(argIndex);
3289 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003290
3291 // Check for using an Objective-C specific conversion specifier
3292 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00003293 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003294 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3295 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003296 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003297
Tom Caree4ee9662010-06-17 19:00:27 +00003298 // Check for invalid use of field width
3299 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00003300 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00003301 startSpecifier, specifierLen);
3302 }
3303
3304 // Check for invalid use of precision
3305 if (!FS.hasValidPrecision()) {
3306 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3307 startSpecifier, specifierLen);
3308 }
3309
3310 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00003311 if (!FS.hasValidThousandsGroupingPrefix())
3312 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003313 if (!FS.hasValidLeadingZeros())
3314 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3315 if (!FS.hasValidPlusPrefix())
3316 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003317 if (!FS.hasValidSpacePrefix())
3318 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003319 if (!FS.hasValidAlternativeForm())
3320 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3321 if (!FS.hasValidLeftJustified())
3322 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3323
3324 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003325 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3326 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3327 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003328 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3329 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3330 startSpecifier, specifierLen);
3331
3332 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003333 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003334 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3335 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003336 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003337 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003338 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003339 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3340 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003341
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003342 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3343 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3344
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003345 // The remaining checks depend on the data arguments.
3346 if (HasVAListArg)
3347 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003348
Ted Kremenek666a1972010-07-26 19:45:42 +00003349 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003350 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003351
Jordan Rose48716662012-07-19 18:10:08 +00003352 const Expr *Arg = getDataArg(argIndex);
3353 if (!Arg)
3354 return true;
3355
3356 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003357}
3358
Jordan Roseec087352012-09-05 22:56:26 +00003359static bool requiresParensToAddCast(const Expr *E) {
3360 // FIXME: We should have a general way to reason about operator
3361 // precedence and whether parens are actually needed here.
3362 // Take care of a few common cases where they aren't.
3363 const Expr *Inside = E->IgnoreImpCasts();
3364 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3365 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3366
3367 switch (Inside->getStmtClass()) {
3368 case Stmt::ArraySubscriptExprClass:
3369 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003370 case Stmt::CharacterLiteralClass:
3371 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003372 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003373 case Stmt::FloatingLiteralClass:
3374 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003375 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003376 case Stmt::ObjCArrayLiteralClass:
3377 case Stmt::ObjCBoolLiteralExprClass:
3378 case Stmt::ObjCBoxedExprClass:
3379 case Stmt::ObjCDictionaryLiteralClass:
3380 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003381 case Stmt::ObjCIvarRefExprClass:
3382 case Stmt::ObjCMessageExprClass:
3383 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003384 case Stmt::ObjCStringLiteralClass:
3385 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003386 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003387 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003388 case Stmt::UnaryOperatorClass:
3389 return false;
3390 default:
3391 return true;
3392 }
3393}
3394
Stephen Hines176edba2014-12-01 14:53:08 -08003395static std::pair<QualType, StringRef>
3396shouldNotPrintDirectly(const ASTContext &Context,
3397 QualType IntendedTy,
3398 const Expr *E) {
3399 // Use a 'while' to peel off layers of typedefs.
3400 QualType TyTy = IntendedTy;
3401 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3402 StringRef Name = UserTy->getDecl()->getName();
3403 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3404 .Case("NSInteger", Context.LongTy)
3405 .Case("NSUInteger", Context.UnsignedLongTy)
3406 .Case("SInt32", Context.IntTy)
3407 .Case("UInt32", Context.UnsignedIntTy)
3408 .Default(QualType());
3409
3410 if (!CastTy.isNull())
3411 return std::make_pair(CastTy, Name);
3412
3413 TyTy = UserTy->desugar();
3414 }
3415
3416 // Strip parens if necessary.
3417 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3418 return shouldNotPrintDirectly(Context,
3419 PE->getSubExpr()->getType(),
3420 PE->getSubExpr());
3421
3422 // If this is a conditional expression, then its result type is constructed
3423 // via usual arithmetic conversions and thus there might be no necessary
3424 // typedef sugar there. Recurse to operands to check for NSInteger &
3425 // Co. usage condition.
3426 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3427 QualType TrueTy, FalseTy;
3428 StringRef TrueName, FalseName;
3429
3430 std::tie(TrueTy, TrueName) =
3431 shouldNotPrintDirectly(Context,
3432 CO->getTrueExpr()->getType(),
3433 CO->getTrueExpr());
3434 std::tie(FalseTy, FalseName) =
3435 shouldNotPrintDirectly(Context,
3436 CO->getFalseExpr()->getType(),
3437 CO->getFalseExpr());
3438
3439 if (TrueTy == FalseTy)
3440 return std::make_pair(TrueTy, TrueName);
3441 else if (TrueTy.isNull())
3442 return std::make_pair(FalseTy, FalseName);
3443 else if (FalseTy.isNull())
3444 return std::make_pair(TrueTy, TrueName);
3445 }
3446
3447 return std::make_pair(QualType(), StringRef());
3448}
3449
Richard Smith831421f2012-06-25 20:30:08 +00003450bool
3451CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3452 const char *StartSpecifier,
3453 unsigned SpecifierLen,
3454 const Expr *E) {
3455 using namespace analyze_format_string;
3456 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003457 // Now type check the data expression that matches the
3458 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003459 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3460 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003461 if (!AT.isValid())
3462 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003463
Jordan Rose448ac3e2012-12-05 18:44:40 +00003464 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003465 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3466 ExprTy = TET->getUnderlyingExpr()->getType();
3467 }
3468
Jordan Rose448ac3e2012-12-05 18:44:40 +00003469 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003470 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003471
Jordan Rose614a8652012-09-05 22:56:19 +00003472 // Look through argument promotions for our error message's reported type.
3473 // This includes the integral and floating promotions, but excludes array
3474 // and function pointer decay; seeing that an argument intended to be a
3475 // string has type 'char [6]' is probably more confusing than 'char *'.
3476 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3477 if (ICE->getCastKind() == CK_IntegralCast ||
3478 ICE->getCastKind() == CK_FloatingCast) {
3479 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003480 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003481
3482 // Check if we didn't match because of an implicit cast from a 'char'
3483 // or 'short' to an 'int'. This is done because printf is a varargs
3484 // function.
3485 if (ICE->getType() == S.Context.IntTy ||
3486 ICE->getType() == S.Context.UnsignedIntTy) {
3487 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003488 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003489 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003490 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003491 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003492 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3493 // Special case for 'a', which has type 'int' in C.
3494 // Note, however, that we do /not/ want to treat multibyte constants like
3495 // 'MooV' as characters! This form is deprecated but still exists.
3496 if (ExprTy == S.Context.IntTy)
3497 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3498 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003499 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003500
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003501 // Look through enums to their underlying type.
3502 bool IsEnum = false;
3503 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3504 ExprTy = EnumTy->getDecl()->getIntegerType();
3505 IsEnum = true;
3506 }
3507
Jordan Rose2cd34402012-12-05 18:44:49 +00003508 // %C in an Objective-C context prints a unichar, not a wchar_t.
3509 // If the argument is an integer of some kind, believe the %C and suggest
3510 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003511 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003512 if (ObjCContext &&
3513 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3514 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3515 !ExprTy->isCharType()) {
3516 // 'unichar' is defined as a typedef of unsigned short, but we should
3517 // prefer using the typedef if it is visible.
3518 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003519
3520 // While we are here, check if the value is an IntegerLiteral that happens
3521 // to be within the valid range.
3522 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3523 const llvm::APInt &V = IL->getValue();
3524 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3525 return true;
3526 }
3527
Jordan Rose2cd34402012-12-05 18:44:49 +00003528 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3529 Sema::LookupOrdinaryName);
3530 if (S.LookupName(Result, S.getCurScope())) {
3531 NamedDecl *ND = Result.getFoundDecl();
3532 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3533 if (TD->getUnderlyingType() == IntendedTy)
3534 IntendedTy = S.Context.getTypedefType(TD);
3535 }
3536 }
3537 }
3538
3539 // Special-case some of Darwin's platform-independence types by suggesting
3540 // casts to primitive types that are known to be large enough.
Stephen Hines176edba2014-12-01 14:53:08 -08003541 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseec087352012-09-05 22:56:26 +00003542 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003543 QualType CastTy;
3544 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3545 if (!CastTy.isNull()) {
3546 IntendedTy = CastTy;
3547 ShouldNotPrintDirectly = true;
Jordan Roseec087352012-09-05 22:56:26 +00003548 }
3549 }
3550
Jordan Rose614a8652012-09-05 22:56:19 +00003551 // We may be able to offer a FixItHint if it is a supported type.
3552 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003553 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003554 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003555
Jordan Rose614a8652012-09-05 22:56:19 +00003556 if (success) {
3557 // Get the fix string from the fixed format specifier
3558 SmallString<16> buf;
3559 llvm::raw_svector_ostream os(buf);
3560 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003561
Jordan Roseec087352012-09-05 22:56:26 +00003562 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3563
Stephen Hines176edba2014-12-01 14:53:08 -08003564 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose2cd34402012-12-05 18:44:49 +00003565 // In this case, the specifier is wrong and should be changed to match
3566 // the argument.
3567 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003568 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3569 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003570 << E->getSourceRange(),
3571 E->getLocStart(),
3572 /*IsStringLocation*/false,
3573 SpecRange,
3574 FixItHint::CreateReplacement(SpecRange, os.str()));
3575
3576 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003577 // The canonical type for formatting this value is different from the
3578 // actual type of the expression. (This occurs, for example, with Darwin's
3579 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3580 // should be printed as 'long' for 64-bit compatibility.)
3581 // Rather than emitting a normal format/argument mismatch, we want to
3582 // add a cast to the recommended type (and correct the format string
3583 // if necessary).
3584 SmallString<16> CastBuf;
3585 llvm::raw_svector_ostream CastFix(CastBuf);
3586 CastFix << "(";
3587 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3588 CastFix << ")";
3589
3590 SmallVector<FixItHint,4> Hints;
3591 if (!AT.matchesType(S.Context, IntendedTy))
3592 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3593
3594 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3595 // If there's already a cast present, just replace it.
3596 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3597 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3598
3599 } else if (!requiresParensToAddCast(E)) {
3600 // If the expression has high enough precedence,
3601 // just write the C-style cast.
3602 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3603 CastFix.str()));
3604 } else {
3605 // Otherwise, add parens around the expression as well as the cast.
3606 CastFix << "(";
3607 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3608 CastFix.str()));
3609
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003610 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseec087352012-09-05 22:56:26 +00003611 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3612 }
3613
Jordan Rose2cd34402012-12-05 18:44:49 +00003614 if (ShouldNotPrintDirectly) {
3615 // The expression has a type that should not be printed directly.
3616 // We extract the name from the typedef because we don't want to show
3617 // the underlying type in the diagnostic.
Stephen Hines176edba2014-12-01 14:53:08 -08003618 StringRef Name;
3619 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3620 Name = TypedefTy->getDecl()->getName();
3621 else
3622 Name = CastTyName;
Jordan Rose2cd34402012-12-05 18:44:49 +00003623 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003624 << Name << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003625 << E->getSourceRange(),
3626 E->getLocStart(), /*IsStringLocation=*/false,
3627 SpecRange, Hints);
3628 } else {
3629 // In this case, the expression could be printed using a different
3630 // specifier, but we've decided that the specifier is probably correct
3631 // and we should cast instead. Just use the normal warning message.
3632 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003633 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3634 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003635 << E->getSourceRange(),
3636 E->getLocStart(), /*IsStringLocation*/false,
3637 SpecRange, Hints);
3638 }
Jordan Roseec087352012-09-05 22:56:26 +00003639 }
Jordan Rose614a8652012-09-05 22:56:19 +00003640 } else {
3641 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3642 SpecifierLen);
3643 // Since the warning for passing non-POD types to variadic functions
3644 // was deferred until now, we emit a warning for non-POD
3645 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003646 switch (S.isValidVarArgType(ExprTy)) {
3647 case Sema::VAK_Valid:
3648 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003649 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003650 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3651 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smith0e218972013-08-05 18:49:43 +00003652 << CSR
3653 << E->getSourceRange(),
3654 E->getLocStart(), /*IsStringLocation*/false, CSR);
3655 break;
3656
3657 case Sema::VAK_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08003658 case Sema::VAK_MSVCUndefined:
Richard Smith0e218972013-08-05 18:49:43 +00003659 EmitFormatDiagnostic(
3660 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003661 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003662 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003663 << CallType
3664 << AT.getRepresentativeTypeName(S.Context)
3665 << CSR
3666 << E->getSourceRange(),
3667 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003668 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003669 break;
3670
3671 case Sema::VAK_Invalid:
3672 if (ExprTy->isObjCObjectType())
3673 EmitFormatDiagnostic(
3674 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3675 << S.getLangOpts().CPlusPlus11
3676 << ExprTy
3677 << CallType
3678 << AT.getRepresentativeTypeName(S.Context)
3679 << CSR
3680 << E->getSourceRange(),
3681 E->getLocStart(), /*IsStringLocation*/false, CSR);
3682 else
3683 // FIXME: If this is an initializer list, suggest removing the braces
3684 // or inserting a cast to the target type.
3685 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3686 << isa<InitListExpr>(E) << ExprTy << CallType
3687 << AT.getRepresentativeTypeName(S.Context)
3688 << E->getSourceRange();
3689 break;
3690 }
3691
3692 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3693 "format string specifier index out of range");
3694 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003695 }
3696
Ted Kremeneke0e53132010-01-28 23:39:18 +00003697 return true;
3698}
3699
Ted Kremenek826a3452010-07-16 02:11:22 +00003700//===--- CHECK: Scanf format string checking ------------------------------===//
3701
3702namespace {
3703class CheckScanfHandler : public CheckFormatHandler {
3704public:
3705 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3706 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003707 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003708 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003709 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003710 Sema::VariadicCallType CallType,
3711 llvm::SmallBitVector &CheckedVarArgs)
3712 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3713 numDataArgs, beg, hasVAListArg,
3714 Args, formatIdx, inFunctionCall, CallType,
3715 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003716 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003717
3718 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3719 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003720 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003721
3722 bool HandleInvalidScanfConversionSpecifier(
3723 const analyze_scanf::ScanfSpecifier &FS,
3724 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003725 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00003726
Stephen Hines651f13c2014-04-23 16:59:28 -07003727 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00003728};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003729}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003730
Ted Kremenekb7c21012010-07-16 18:28:03 +00003731void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3732 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003733 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3734 getLocationOfByte(end), /*IsStringLocation*/true,
3735 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003736}
3737
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003738bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3739 const analyze_scanf::ScanfSpecifier &FS,
3740 const char *startSpecifier,
3741 unsigned specifierLen) {
3742
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003743 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003744 FS.getConversionSpecifier();
3745
3746 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3747 getLocationOfByte(CS.getStart()),
3748 startSpecifier, specifierLen,
3749 CS.getStart(), CS.getLength());
3750}
3751
Ted Kremenek826a3452010-07-16 02:11:22 +00003752bool CheckScanfHandler::HandleScanfSpecifier(
3753 const analyze_scanf::ScanfSpecifier &FS,
3754 const char *startSpecifier,
3755 unsigned specifierLen) {
3756
3757 using namespace analyze_scanf;
3758 using namespace analyze_format_string;
3759
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003760 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003761
Ted Kremenekbaa40062010-07-19 22:01:06 +00003762 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3763 // be used to decide if we are using positional arguments consistently.
3764 if (FS.consumesDataArgument()) {
3765 if (atFirstArg) {
3766 atFirstArg = false;
3767 usesPositionalArgs = FS.usesPositionalArg();
3768 }
3769 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003770 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3771 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003772 return false;
3773 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003774 }
3775
3776 // Check if the field with is non-zero.
3777 const OptionalAmount &Amt = FS.getFieldWidth();
3778 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3779 if (Amt.getConstantAmount() == 0) {
3780 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3781 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003782 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3783 getLocationOfByte(Amt.getStart()),
3784 /*IsStringLocation*/true, R,
3785 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003786 }
3787 }
3788
3789 if (!FS.consumesDataArgument()) {
3790 // FIXME: Technically specifying a precision or field width here
3791 // makes no sense. Worth issuing a warning at some point.
3792 return true;
3793 }
3794
3795 // Consume the argument.
3796 unsigned argIndex = FS.getArgIndex();
3797 if (argIndex < NumDataArgs) {
3798 // The check to see if the argIndex is valid will come later.
3799 // We set the bit here because we may exit early from this
3800 // function if we encounter some other error.
3801 CoveredArgs.set(argIndex);
3802 }
3803
Ted Kremenek1e51c202010-07-20 20:04:47 +00003804 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003805 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003806 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3807 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003808 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003809 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003810 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003811 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3812 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003813
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003814 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3815 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3816
Ted Kremenek826a3452010-07-16 02:11:22 +00003817 // The remaining checks depend on the data arguments.
3818 if (HasVAListArg)
3819 return true;
3820
Ted Kremenek666a1972010-07-26 19:45:42 +00003821 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003822 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003823
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003824 // Check that the argument type matches the format specifier.
3825 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003826 if (!Ex)
3827 return true;
3828
Hans Wennborg58e1e542012-08-07 08:59:46 +00003829 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3830 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003831 ScanfSpecifier fixedFS = FS;
Stephen Hines651f13c2014-04-23 16:59:28 -07003832 bool success = fixedFS.fixType(Ex->getType(),
3833 Ex->IgnoreImpCasts()->getType(),
3834 S.getLangOpts(), S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003835
3836 if (success) {
3837 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003838 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003839 llvm::raw_svector_ostream os(buf);
3840 fixedFS.toString(os);
3841
3842 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003843 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3844 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003845 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003846 Ex->getLocStart(),
3847 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003848 getSpecifierRange(startSpecifier, specifierLen),
3849 FixItHint::CreateReplacement(
3850 getSpecifierRange(startSpecifier, specifierLen),
3851 os.str()));
3852 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003853 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003854 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3855 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003856 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003857 Ex->getLocStart(),
3858 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003859 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003860 }
3861 }
3862
Ted Kremenek826a3452010-07-16 02:11:22 +00003863 return true;
3864}
3865
3866void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003867 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003868 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003869 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003870 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003871 bool inFunctionCall, VariadicCallType CallType,
3872 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003873
Ted Kremeneke0e53132010-01-28 23:39:18 +00003874 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003875 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003876 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003877 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003878 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3879 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003880 return;
3881 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003882
Ted Kremeneke0e53132010-01-28 23:39:18 +00003883 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003884 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003885 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07003886 // Account for cases where the string literal is truncated in a declaration.
3887 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3888 assert(T && "String literal not of constant array type!");
3889 size_t TypeSize = T->getSize().getZExtValue();
3890 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003891 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07003892
3893 // Emit a warning if the string literal is truncated and does not contain an
3894 // embedded null character.
3895 if (TypeSize <= StrRef.size() &&
3896 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3897 CheckFormatHandler::EmitFormatDiagnostic(
3898 *this, inFunctionCall, Args[format_idx],
3899 PDiag(diag::warn_printf_format_string_not_null_terminated),
3900 FExpr->getLocStart(),
3901 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3902 return;
3903 }
3904
Ted Kremeneke0e53132010-01-28 23:39:18 +00003905 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003906 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003907 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003908 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003909 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3910 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003911 return;
3912 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003913
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003914 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003915 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003916 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003917 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003918 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003919
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003920 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003921 getLangOpts(),
3922 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003923 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003924 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003925 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003926 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003927 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003928
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003929 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003930 getLangOpts(),
3931 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003932 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003933 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003934}
3935
Stephen Hines176edba2014-12-01 14:53:08 -08003936bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
3937 // Str - The format string. NOTE: this is NOT null-terminated!
3938 StringRef StrRef = FExpr->getString();
3939 const char *Str = StrRef.data();
3940 // Account for cases where the string literal is truncated in a declaration.
3941 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3942 assert(T && "String literal not of constant array type!");
3943 size_t TypeSize = T->getSize().getZExtValue();
3944 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3945 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
3946 getLangOpts(),
3947 Context.getTargetInfo());
3948}
3949
Stephen Hines651f13c2014-04-23 16:59:28 -07003950//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3951
3952// Returns the related absolute value function that is larger, of 0 if one
3953// does not exist.
3954static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3955 switch (AbsFunction) {
3956 default:
3957 return 0;
3958
3959 case Builtin::BI__builtin_abs:
3960 return Builtin::BI__builtin_labs;
3961 case Builtin::BI__builtin_labs:
3962 return Builtin::BI__builtin_llabs;
3963 case Builtin::BI__builtin_llabs:
3964 return 0;
3965
3966 case Builtin::BI__builtin_fabsf:
3967 return Builtin::BI__builtin_fabs;
3968 case Builtin::BI__builtin_fabs:
3969 return Builtin::BI__builtin_fabsl;
3970 case Builtin::BI__builtin_fabsl:
3971 return 0;
3972
3973 case Builtin::BI__builtin_cabsf:
3974 return Builtin::BI__builtin_cabs;
3975 case Builtin::BI__builtin_cabs:
3976 return Builtin::BI__builtin_cabsl;
3977 case Builtin::BI__builtin_cabsl:
3978 return 0;
3979
3980 case Builtin::BIabs:
3981 return Builtin::BIlabs;
3982 case Builtin::BIlabs:
3983 return Builtin::BIllabs;
3984 case Builtin::BIllabs:
3985 return 0;
3986
3987 case Builtin::BIfabsf:
3988 return Builtin::BIfabs;
3989 case Builtin::BIfabs:
3990 return Builtin::BIfabsl;
3991 case Builtin::BIfabsl:
3992 return 0;
3993
3994 case Builtin::BIcabsf:
3995 return Builtin::BIcabs;
3996 case Builtin::BIcabs:
3997 return Builtin::BIcabsl;
3998 case Builtin::BIcabsl:
3999 return 0;
4000 }
4001}
4002
4003// Returns the argument type of the absolute value function.
4004static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4005 unsigned AbsType) {
4006 if (AbsType == 0)
4007 return QualType();
4008
4009 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4010 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4011 if (Error != ASTContext::GE_None)
4012 return QualType();
4013
4014 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4015 if (!FT)
4016 return QualType();
4017
4018 if (FT->getNumParams() != 1)
4019 return QualType();
4020
4021 return FT->getParamType(0);
4022}
4023
4024// Returns the best absolute value function, or zero, based on type and
4025// current absolute value function.
4026static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4027 unsigned AbsFunctionKind) {
4028 unsigned BestKind = 0;
4029 uint64_t ArgSize = Context.getTypeSize(ArgType);
4030 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4031 Kind = getLargerAbsoluteValueFunction(Kind)) {
4032 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4033 if (Context.getTypeSize(ParamType) >= ArgSize) {
4034 if (BestKind == 0)
4035 BestKind = Kind;
4036 else if (Context.hasSameType(ParamType, ArgType)) {
4037 BestKind = Kind;
4038 break;
4039 }
4040 }
4041 }
4042 return BestKind;
4043}
4044
4045enum AbsoluteValueKind {
4046 AVK_Integer,
4047 AVK_Floating,
4048 AVK_Complex
4049};
4050
4051static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4052 if (T->isIntegralOrEnumerationType())
4053 return AVK_Integer;
4054 if (T->isRealFloatingType())
4055 return AVK_Floating;
4056 if (T->isAnyComplexType())
4057 return AVK_Complex;
4058
4059 llvm_unreachable("Type not integer, floating, or complex");
4060}
4061
4062// Changes the absolute value function to a different type. Preserves whether
4063// the function is a builtin.
4064static unsigned changeAbsFunction(unsigned AbsKind,
4065 AbsoluteValueKind ValueKind) {
4066 switch (ValueKind) {
4067 case AVK_Integer:
4068 switch (AbsKind) {
4069 default:
4070 return 0;
4071 case Builtin::BI__builtin_fabsf:
4072 case Builtin::BI__builtin_fabs:
4073 case Builtin::BI__builtin_fabsl:
4074 case Builtin::BI__builtin_cabsf:
4075 case Builtin::BI__builtin_cabs:
4076 case Builtin::BI__builtin_cabsl:
4077 return Builtin::BI__builtin_abs;
4078 case Builtin::BIfabsf:
4079 case Builtin::BIfabs:
4080 case Builtin::BIfabsl:
4081 case Builtin::BIcabsf:
4082 case Builtin::BIcabs:
4083 case Builtin::BIcabsl:
4084 return Builtin::BIabs;
4085 }
4086 case AVK_Floating:
4087 switch (AbsKind) {
4088 default:
4089 return 0;
4090 case Builtin::BI__builtin_abs:
4091 case Builtin::BI__builtin_labs:
4092 case Builtin::BI__builtin_llabs:
4093 case Builtin::BI__builtin_cabsf:
4094 case Builtin::BI__builtin_cabs:
4095 case Builtin::BI__builtin_cabsl:
4096 return Builtin::BI__builtin_fabsf;
4097 case Builtin::BIabs:
4098 case Builtin::BIlabs:
4099 case Builtin::BIllabs:
4100 case Builtin::BIcabsf:
4101 case Builtin::BIcabs:
4102 case Builtin::BIcabsl:
4103 return Builtin::BIfabsf;
4104 }
4105 case AVK_Complex:
4106 switch (AbsKind) {
4107 default:
4108 return 0;
4109 case Builtin::BI__builtin_abs:
4110 case Builtin::BI__builtin_labs:
4111 case Builtin::BI__builtin_llabs:
4112 case Builtin::BI__builtin_fabsf:
4113 case Builtin::BI__builtin_fabs:
4114 case Builtin::BI__builtin_fabsl:
4115 return Builtin::BI__builtin_cabsf;
4116 case Builtin::BIabs:
4117 case Builtin::BIlabs:
4118 case Builtin::BIllabs:
4119 case Builtin::BIfabsf:
4120 case Builtin::BIfabs:
4121 case Builtin::BIfabsl:
4122 return Builtin::BIcabsf;
4123 }
4124 }
4125 llvm_unreachable("Unable to convert function");
4126}
4127
4128static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4129 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4130 if (!FnInfo)
4131 return 0;
4132
4133 switch (FDecl->getBuiltinID()) {
4134 default:
4135 return 0;
4136 case Builtin::BI__builtin_abs:
4137 case Builtin::BI__builtin_fabs:
4138 case Builtin::BI__builtin_fabsf:
4139 case Builtin::BI__builtin_fabsl:
4140 case Builtin::BI__builtin_labs:
4141 case Builtin::BI__builtin_llabs:
4142 case Builtin::BI__builtin_cabs:
4143 case Builtin::BI__builtin_cabsf:
4144 case Builtin::BI__builtin_cabsl:
4145 case Builtin::BIabs:
4146 case Builtin::BIlabs:
4147 case Builtin::BIllabs:
4148 case Builtin::BIfabs:
4149 case Builtin::BIfabsf:
4150 case Builtin::BIfabsl:
4151 case Builtin::BIcabs:
4152 case Builtin::BIcabsf:
4153 case Builtin::BIcabsl:
4154 return FDecl->getBuiltinID();
4155 }
4156 llvm_unreachable("Unknown Builtin type");
4157}
4158
4159// If the replacement is valid, emit a note with replacement function.
4160// Additionally, suggest including the proper header if not already included.
4161static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004162 unsigned AbsKind, QualType ArgType) {
4163 bool EmitHeaderHint = true;
4164 const char *HeaderName = nullptr;
4165 const char *FunctionName = nullptr;
4166 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4167 FunctionName = "std::abs";
4168 if (ArgType->isIntegralOrEnumerationType()) {
4169 HeaderName = "cstdlib";
4170 } else if (ArgType->isRealFloatingType()) {
4171 HeaderName = "cmath";
4172 } else {
4173 llvm_unreachable("Invalid Type");
Stephen Hines651f13c2014-04-23 16:59:28 -07004174 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004175
4176 // Lookup all std::abs
4177 if (NamespaceDecl *Std = S.getStdNamespace()) {
4178 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4179 R.suppressDiagnostics();
4180 S.LookupQualifiedName(R, Std);
4181
4182 for (const auto *I : R) {
4183 const FunctionDecl *FDecl = nullptr;
4184 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4185 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4186 } else {
4187 FDecl = dyn_cast<FunctionDecl>(I);
4188 }
4189 if (!FDecl)
4190 continue;
4191
4192 // Found std::abs(), check that they are the right ones.
4193 if (FDecl->getNumParams() != 1)
4194 continue;
4195
4196 // Check that the parameter type can handle the argument.
4197 QualType ParamType = FDecl->getParamDecl(0)->getType();
4198 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4199 S.Context.getTypeSize(ArgType) <=
4200 S.Context.getTypeSize(ParamType)) {
4201 // Found a function, don't need the header hint.
4202 EmitHeaderHint = false;
4203 break;
4204 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004205 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004206 }
4207 } else {
4208 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4209 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4210
4211 if (HeaderName) {
4212 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4213 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4214 R.suppressDiagnostics();
4215 S.LookupName(R, S.getCurScope());
4216
4217 if (R.isSingleResult()) {
4218 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4219 if (FD && FD->getBuiltinID() == AbsKind) {
4220 EmitHeaderHint = false;
4221 } else {
4222 return;
4223 }
4224 } else if (!R.empty()) {
4225 return;
4226 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004227 }
4228 }
4229
4230 S.Diag(Loc, diag::note_replace_abs_function)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004231 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Stephen Hines651f13c2014-04-23 16:59:28 -07004232
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004233 if (!HeaderName)
4234 return;
4235
4236 if (!EmitHeaderHint)
4237 return;
4238
Stephen Hines176edba2014-12-01 14:53:08 -08004239 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4240 << FunctionName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004241}
4242
4243static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4244 if (!FDecl)
4245 return false;
4246
4247 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4248 return false;
4249
4250 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4251
4252 while (ND && ND->isInlineNamespace()) {
4253 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004254 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004255
4256 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4257 return false;
4258
4259 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4260 return false;
4261
4262 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004263}
4264
4265// Warn when using the wrong abs() function.
4266void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4267 const FunctionDecl *FDecl,
4268 IdentifierInfo *FnInfo) {
4269 if (Call->getNumArgs() != 1)
4270 return;
4271
4272 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004273 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4274 if (AbsKind == 0 && !IsStdAbs)
Stephen Hines651f13c2014-04-23 16:59:28 -07004275 return;
4276
4277 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4278 QualType ParamType = Call->getArg(0)->getType();
4279
Stephen Hines176edba2014-12-01 14:53:08 -08004280 // Unsigned types cannot be negative. Suggest removing the absolute value
4281 // function call.
Stephen Hines651f13c2014-04-23 16:59:28 -07004282 if (ArgType->isUnsignedIntegerType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004283 const char *FunctionName =
4284 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07004285 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4286 Diag(Call->getExprLoc(), diag::note_remove_abs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004287 << FunctionName
Stephen Hines651f13c2014-04-23 16:59:28 -07004288 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4289 return;
4290 }
4291
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004292 // std::abs has overloads which prevent most of the absolute value problems
4293 // from occurring.
4294 if (IsStdAbs)
4295 return;
4296
Stephen Hines651f13c2014-04-23 16:59:28 -07004297 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4298 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4299
4300 // The argument and parameter are the same kind. Check if they are the right
4301 // size.
4302 if (ArgValueKind == ParamValueKind) {
4303 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4304 return;
4305
4306 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4307 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4308 << FDecl << ArgType << ParamType;
4309
4310 if (NewAbsKind == 0)
4311 return;
4312
4313 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004314 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004315 return;
4316 }
4317
4318 // ArgValueKind != ParamValueKind
4319 // The wrong type of absolute value function was used. Attempt to find the
4320 // proper one.
4321 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4322 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4323 if (NewAbsKind == 0)
4324 return;
4325
4326 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4327 << FDecl << ParamValueKind << ArgValueKind;
4328
4329 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004330 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004331 return;
4332}
4333
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004334//===--- CHECK: Standard memory functions ---------------------------------===//
4335
Stephen Hines651f13c2014-04-23 16:59:28 -07004336/// \brief Takes the expression passed to the size_t parameter of functions
4337/// such as memcmp, strncat, etc and warns if it's a comparison.
4338///
4339/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4340static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4341 IdentifierInfo *FnName,
4342 SourceLocation FnLoc,
4343 SourceLocation RParenLoc) {
4344 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4345 if (!Size)
4346 return false;
4347
4348 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4349 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4350 return false;
4351
Stephen Hines651f13c2014-04-23 16:59:28 -07004352 SourceRange SizeRange = Size->getSourceRange();
4353 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4354 << SizeRange << FnName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004355 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4356 << FnName << FixItHint::CreateInsertion(
4357 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Stephen Hines651f13c2014-04-23 16:59:28 -07004358 << FixItHint::CreateRemoval(RParenLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004359 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Stephen Hines651f13c2014-04-23 16:59:28 -07004360 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004361 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4362 ")");
Stephen Hines651f13c2014-04-23 16:59:28 -07004363
4364 return true;
4365}
4366
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004367/// \brief Determine whether the given type is or contains a dynamic class type
4368/// (e.g., whether it has a vtable).
4369static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4370 bool &IsContained) {
4371 // Look through array types while ignoring qualifiers.
4372 const Type *Ty = T->getBaseElementTypeUnsafe();
4373 IsContained = false;
4374
4375 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4376 RD = RD ? RD->getDefinition() : nullptr;
4377 if (!RD)
4378 return nullptr;
4379
4380 if (RD->isDynamicClass())
4381 return RD;
4382
4383 // Check all the fields. If any bases were dynamic, the class is dynamic.
4384 // It's impossible for a class to transitively contain itself by value, so
4385 // infinite recursion is impossible.
4386 for (auto *FD : RD->fields()) {
4387 bool SubContained;
4388 if (const CXXRecordDecl *ContainedRD =
4389 getContainedDynamicClass(FD->getType(), SubContained)) {
4390 IsContained = true;
4391 return ContainedRD;
4392 }
4393 }
4394
4395 return nullptr;
Douglas Gregor2a053a32011-05-03 20:05:22 +00004396}
4397
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004398/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00004399/// otherwise returns NULL.
4400static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00004401 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00004402 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4403 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4404 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004405
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004406 return nullptr;
Chandler Carruth000d4282011-06-16 09:09:40 +00004407}
4408
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004409/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00004410static QualType getSizeOfArgType(const Expr* E) {
4411 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4412 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4413 if (SizeOf->getKind() == clang::UETT_SizeOf)
4414 return SizeOf->getTypeOfArgument();
4415
4416 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00004417}
4418
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004419/// \brief Check for dangerous or invalid arguments to memset().
4420///
Chandler Carruth929f0132011-06-03 06:23:57 +00004421/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004422/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4423/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004424///
4425/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004426void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004427 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004428 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004429 assert(BId != 0);
4430
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004431 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004432 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004433 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004434 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004435 return;
4436
Anna Zaks0a151a12012-01-17 00:37:07 +00004437 unsigned LastArg = (BId == Builtin::BImemset ||
4438 BId == Builtin::BIstrndup ? 1 : 2);
4439 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004440 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004441
Stephen Hines651f13c2014-04-23 16:59:28 -07004442 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4443 Call->getLocStart(), Call->getRParenLoc()))
4444 return;
4445
Chandler Carruth000d4282011-06-16 09:09:40 +00004446 // We have special checking when the length is a sizeof expression.
4447 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4448 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4449 llvm::FoldingSetNodeID SizeOfArgID;
4450
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004451 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4452 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004453 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004454
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004455 QualType DestTy = Dest->getType();
4456 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4457 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004458
Chandler Carruth000d4282011-06-16 09:09:40 +00004459 // Never warn about void type pointers. This can be used to suppress
4460 // false positives.
4461 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004462 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004463
Chandler Carruth000d4282011-06-16 09:09:40 +00004464 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4465 // actually comparing the expressions for equality. Because computing the
4466 // expression IDs can be expensive, we only do this if the diagnostic is
4467 // enabled.
4468 if (SizeOfArg &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004469 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4470 SizeOfArg->getExprLoc())) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004471 // We only compute IDs for expressions if the warning is enabled, and
4472 // cache the sizeof arg's ID.
4473 if (SizeOfArgID == llvm::FoldingSetNodeID())
4474 SizeOfArg->Profile(SizeOfArgID, Context, true);
4475 llvm::FoldingSetNodeID DestID;
4476 Dest->Profile(DestID, Context, true);
4477 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004478 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4479 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004480 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004481 StringRef ReadableName = FnName->getName();
4482
Chandler Carruth000d4282011-06-16 09:09:40 +00004483 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004484 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004485 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004486 if (!PointeeTy->isIncompleteType() &&
4487 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004488 ActionIdx = 2; // If the pointee's size is sizeof(char),
4489 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004490
4491 // If the function is defined as a builtin macro, do not show macro
4492 // expansion.
4493 SourceLocation SL = SizeOfArg->getExprLoc();
4494 SourceRange DSR = Dest->getSourceRange();
4495 SourceRange SSR = SizeOfArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004496 SourceManager &SM = getSourceManager();
Anna Zaks6fcb3722012-05-30 00:34:21 +00004497
4498 if (SM.isMacroArgExpansion(SL)) {
4499 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4500 SL = SM.getSpellingLoc(SL);
4501 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4502 SM.getSpellingLoc(DSR.getEnd()));
4503 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4504 SM.getSpellingLoc(SSR.getEnd()));
4505 }
4506
Anna Zaks90c78322012-05-30 23:14:52 +00004507 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004508 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004509 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004510 << PointeeTy
4511 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004512 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004513 << SSR);
4514 DiagRuntimeBehavior(SL, SizeOfArg,
4515 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4516 << ActionIdx
4517 << SSR);
4518
Chandler Carruth000d4282011-06-16 09:09:40 +00004519 break;
4520 }
4521 }
4522
4523 // Also check for cases where the sizeof argument is the exact same
4524 // type as the memory argument, and where it points to a user-defined
4525 // record type.
4526 if (SizeOfArgTy != QualType()) {
4527 if (PointeeTy->isRecordType() &&
4528 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4529 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4530 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4531 << FnName << SizeOfArgTy << ArgIdx
4532 << PointeeTy << Dest->getSourceRange()
4533 << LenExpr->getSourceRange());
4534 break;
4535 }
Nico Webere4a1c642011-06-14 16:14:58 +00004536 }
4537
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004538 // Always complain about dynamic classes.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004539 bool IsContained;
4540 if (const CXXRecordDecl *ContainedRD =
4541 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004542
4543 unsigned OperationType = 0;
4544 // "overwritten" if we're warning about the destination for any call
4545 // but memcmp; otherwise a verb appropriate to the call.
4546 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4547 if (BId == Builtin::BImemcpy)
4548 OperationType = 1;
4549 else if(BId == Builtin::BImemmove)
4550 OperationType = 2;
4551 else if (BId == Builtin::BImemcmp)
4552 OperationType = 3;
4553 }
4554
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004555 DiagRuntimeBehavior(
4556 Dest->getExprLoc(), Dest,
4557 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00004558 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004559 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004560 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00004561 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4562 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004563 DiagRuntimeBehavior(
4564 Dest->getExprLoc(), Dest,
4565 PDiag(diag::warn_arc_object_memaccess)
4566 << ArgIdx << FnName << PointeeTy
4567 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00004568 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004569 continue;
John McCallf85e1932011-06-15 23:02:42 +00004570
4571 DiagRuntimeBehavior(
4572 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00004573 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004574 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4575 break;
4576 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004577 }
4578}
4579
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004580// A little helper routine: ignore addition and subtraction of integer literals.
4581// This intentionally does not ignore all integer constant expressions because
4582// we don't want to remove sizeof().
4583static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4584 Ex = Ex->IgnoreParenCasts();
4585
4586 for (;;) {
4587 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4588 if (!BO || !BO->isAdditiveOp())
4589 break;
4590
4591 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4592 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4593
4594 if (isa<IntegerLiteral>(RHS))
4595 Ex = LHS;
4596 else if (isa<IntegerLiteral>(LHS))
4597 Ex = RHS;
4598 else
4599 break;
4600 }
4601
4602 return Ex;
4603}
4604
Anna Zaks0f38ace2012-08-08 21:42:23 +00004605static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4606 ASTContext &Context) {
4607 // Only handle constant-sized or VLAs, but not flexible members.
4608 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4609 // Only issue the FIXIT for arrays of size > 1.
4610 if (CAT->getSize().getSExtValue() <= 1)
4611 return false;
4612 } else if (!Ty->isVariableArrayType()) {
4613 return false;
4614 }
4615 return true;
4616}
4617
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004618// Warn if the user has made the 'size' argument to strlcpy or strlcat
4619// be the size of the source, instead of the destination.
4620void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4621 IdentifierInfo *FnName) {
4622
4623 // Don't crash if the user has the wrong number of arguments
Stephen Hines176edba2014-12-01 14:53:08 -08004624 unsigned NumArgs = Call->getNumArgs();
4625 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004626 return;
4627
4628 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4629 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004630 const Expr *CompareWithSrc = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004631
4632 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4633 Call->getLocStart(), Call->getRParenLoc()))
4634 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004635
4636 // Look for 'strlcpy(dst, x, sizeof(x))'
4637 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4638 CompareWithSrc = Ex;
4639 else {
4640 // Look for 'strlcpy(dst, x, strlen(x))'
4641 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004642 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4643 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004644 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4645 }
4646 }
4647
4648 if (!CompareWithSrc)
4649 return;
4650
4651 // Determine if the argument to sizeof/strlen is equal to the source
4652 // argument. In principle there's all kinds of things you could do
4653 // here, for instance creating an == expression and evaluating it with
4654 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4655 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4656 if (!SrcArgDRE)
4657 return;
4658
4659 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4660 if (!CompareWithSrcDRE ||
4661 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4662 return;
4663
4664 const Expr *OriginalSizeArg = Call->getArg(2);
4665 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4666 << OriginalSizeArg->getSourceRange() << FnName;
4667
4668 // Output a FIXIT hint if the destination is an array (rather than a
4669 // pointer to an array). This could be enhanced to handle some
4670 // pointers if we know the actual size, like if DstArg is 'array+2'
4671 // we could say 'sizeof(array)-2'.
4672 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00004673 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00004674 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00004675
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004676 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00004677 llvm::raw_svector_ostream OS(sizeString);
4678 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004679 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00004680 OS << ")";
4681
4682 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4683 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4684 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004685}
4686
Anna Zaksc36bedc2012-02-01 19:08:57 +00004687/// Check if two expressions refer to the same declaration.
4688static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4689 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4690 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4691 return D1->getDecl() == D2->getDecl();
4692 return false;
4693}
4694
4695static const Expr *getStrlenExprArg(const Expr *E) {
4696 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4697 const FunctionDecl *FD = CE->getDirectCallee();
4698 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004699 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004700 return CE->getArg(0)->IgnoreParenCasts();
4701 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004702 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004703}
4704
4705// Warn on anti-patterns as the 'size' argument to strncat.
4706// The correct size argument should look like following:
4707// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4708void Sema::CheckStrncatArguments(const CallExpr *CE,
4709 IdentifierInfo *FnName) {
4710 // Don't crash if the user has the wrong number of arguments.
4711 if (CE->getNumArgs() < 3)
4712 return;
4713 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4714 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4715 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4716
Stephen Hines651f13c2014-04-23 16:59:28 -07004717 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4718 CE->getRParenLoc()))
4719 return;
4720
Anna Zaksc36bedc2012-02-01 19:08:57 +00004721 // Identify common expressions, which are wrongly used as the size argument
4722 // to strncat and may lead to buffer overflows.
4723 unsigned PatternType = 0;
4724 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4725 // - sizeof(dst)
4726 if (referToTheSameDecl(SizeOfArg, DstArg))
4727 PatternType = 1;
4728 // - sizeof(src)
4729 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4730 PatternType = 2;
4731 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4732 if (BE->getOpcode() == BO_Sub) {
4733 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4734 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4735 // - sizeof(dst) - strlen(dst)
4736 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4737 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4738 PatternType = 1;
4739 // - sizeof(src) - (anything)
4740 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4741 PatternType = 2;
4742 }
4743 }
4744
4745 if (PatternType == 0)
4746 return;
4747
Anna Zaksafdb0412012-02-03 01:27:37 +00004748 // Generate the diagnostic.
4749 SourceLocation SL = LenArg->getLocStart();
4750 SourceRange SR = LenArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004751 SourceManager &SM = getSourceManager();
Anna Zaksafdb0412012-02-03 01:27:37 +00004752
4753 // If the function is defined as a builtin macro, do not show macro expansion.
4754 if (SM.isMacroArgExpansion(SL)) {
4755 SL = SM.getSpellingLoc(SL);
4756 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4757 SM.getSpellingLoc(SR.getEnd()));
4758 }
4759
Anna Zaks0f38ace2012-08-08 21:42:23 +00004760 // Check if the destination is an array (rather than a pointer to an array).
4761 QualType DstTy = DstArg->getType();
4762 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4763 Context);
4764 if (!isKnownSizeArray) {
4765 if (PatternType == 1)
4766 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4767 else
4768 Diag(SL, diag::warn_strncat_src_size) << SR;
4769 return;
4770 }
4771
Anna Zaksc36bedc2012-02-01 19:08:57 +00004772 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00004773 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004774 else
Anna Zaksafdb0412012-02-03 01:27:37 +00004775 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004776
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004777 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004778 llvm::raw_svector_ostream OS(sizeString);
4779 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004780 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004781 OS << ") - ";
4782 OS << "strlen(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004783 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004784 OS << ") - 1";
4785
Anna Zaksafdb0412012-02-03 01:27:37 +00004786 Diag(SL, diag::note_strncat_wrong_size)
4787 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004788}
4789
Ted Kremenek06de2762007-08-17 16:46:58 +00004790//===--- CHECK: Return Address of Stack Variable --------------------------===//
4791
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004792static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4793 Decl *ParentDecl);
4794static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4795 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004796
4797/// CheckReturnStackAddr - Check if a return statement returns the address
4798/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07004799static void
4800CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4801 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004803 Expr *stackE = nullptr;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004804 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004805
4806 // Perform checking for returned stack addresses, local blocks,
4807 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00004808 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07004809 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004810 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004811 } else if (lhsType->isReferenceType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004812 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004813 }
4814
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004815 if (!stackE)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004816 return; // Nothing suspicious was found.
4817
4818 SourceLocation diagLoc;
4819 SourceRange diagRange;
4820 if (refVars.empty()) {
4821 diagLoc = stackE->getLocStart();
4822 diagRange = stackE->getSourceRange();
4823 } else {
4824 // We followed through a reference variable. 'stackE' contains the
4825 // problematic expression but we will warn at the return statement pointing
4826 // at the reference variable. We will later display the "trail" of
4827 // reference variables using notes.
4828 diagLoc = refVars[0]->getLocStart();
4829 diagRange = refVars[0]->getSourceRange();
4830 }
4831
4832 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07004833 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004834 : diag::warn_ret_stack_addr)
4835 << DR->getDecl()->getDeclName() << diagRange;
4836 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07004837 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004838 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07004839 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004840 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07004841 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4842 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004843 << diagRange;
4844 }
4845
4846 // Display the "trail" of reference variables that we followed until we
4847 // found the problematic expression using notes.
4848 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4849 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4850 // If this var binds to another reference var, show the range of the next
4851 // var, otherwise the var binds to the problematic expression, in which case
4852 // show the range of the expression.
4853 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4854 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07004855 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4856 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004857 }
4858}
4859
4860/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4861/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004862/// to a location on the stack, a local block, an address of a label, or a
4863/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004864/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004865/// encounter a subexpression that (1) clearly does not lead to one of the
4866/// above problematic expressions (2) is something we cannot determine leads to
4867/// a problematic expression based on such local checking.
4868///
4869/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4870/// the expression that they point to. Such variables are added to the
4871/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004872///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004873/// EvalAddr processes expressions that are pointers that are used as
4874/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004875/// At the base case of the recursion is a check for the above problematic
4876/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004877///
4878/// This implementation handles:
4879///
4880/// * pointer-to-pointer casts
4881/// * implicit conversions from array references to pointers
4882/// * taking the address of fields
4883/// * arbitrary interplay between "&" and "*" operators
4884/// * pointer arithmetic from an address of a stack variable
4885/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004886static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4887 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004888 if (E->isTypeDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004889 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004890
Ted Kremenek06de2762007-08-17 16:46:58 +00004891 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004892 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004893 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004894 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004895 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004896
Peter Collingbournef111d932011-04-15 00:35:48 +00004897 E = E->IgnoreParens();
4898
Ted Kremenek06de2762007-08-17 16:46:58 +00004899 // Our "symbolic interpreter" is just a dispatch off the currently
4900 // viewed AST node. We then recursively traverse the AST by calling
4901 // EvalAddr and EvalVal appropriately.
4902 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004903 case Stmt::DeclRefExprClass: {
4904 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4905
Stephen Hines651f13c2014-04-23 16:59:28 -07004906 // If we leave the immediate function, the lifetime isn't about to end.
4907 if (DR->refersToEnclosingLocal())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004908 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004909
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004910 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4911 // If this is a reference variable, follow through to the expression that
4912 // it points to.
4913 if (V->hasLocalStorage() &&
4914 V->getType()->isReferenceType() && V->hasInit()) {
4915 // Add the reference variable to the "trail".
4916 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004917 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004918 }
4919
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004920 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004921 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004922
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004923 case Stmt::UnaryOperatorClass: {
4924 // The only unary operator that make sense to handle here
4925 // is AddrOf. All others don't make sense as pointers.
4926 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004927
John McCall2de56d12010-08-25 11:45:40 +00004928 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004929 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004930 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004931 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00004932 }
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004934 case Stmt::BinaryOperatorClass: {
4935 // Handle pointer arithmetic. All other binary operators are not valid
4936 // in this context.
4937 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004938 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004939
John McCall2de56d12010-08-25 11:45:40 +00004940 if (op != BO_Add && op != BO_Sub)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004941 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004942
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004943 Expr *Base = B->getLHS();
4944
4945 // Determine which argument is the real pointer base. It could be
4946 // the RHS argument instead of the LHS.
4947 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004948
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004949 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004950 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004951 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004952
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004953 // For conditional operators we need to see if either the LHS or RHS are
4954 // valid DeclRefExpr*s. If one of them is valid, we return it.
4955 case Stmt::ConditionalOperatorClass: {
4956 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004957
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004958 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07004959 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4960 if (Expr *LHSExpr = C->getLHS()) {
4961 // In C++, we can have a throw-expression, which has 'void' type.
4962 if (!LHSExpr->getType()->isVoidType())
4963 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004964 return LHS;
4965 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004966
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004967 // In C++, we can have a throw-expression, which has 'void' type.
4968 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004969 return nullptr;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004970
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004971 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004972 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004973
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004974 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004975 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004976 return E; // local block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004977 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004978
4979 case Stmt::AddrLabelExprClass:
4980 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004981
John McCall80ee6e82011-11-10 05:35:25 +00004982 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004983 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4984 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004985
Ted Kremenek54b52742008-08-07 00:49:01 +00004986 // For casts, we need to handle conversions from arrays to
4987 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004988 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004989 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004990 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004991 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004992 case Stmt::CXXStaticCastExprClass:
4993 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004994 case Stmt::CXXConstCastExprClass:
4995 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004996 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4997 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004998 case CK_LValueToRValue:
4999 case CK_NoOp:
5000 case CK_BaseToDerived:
5001 case CK_DerivedToBase:
5002 case CK_UncheckedDerivedToBase:
5003 case CK_Dynamic:
5004 case CK_CPointerToObjCPointerCast:
5005 case CK_BlockPointerToObjCPointerCast:
5006 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005007 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005008
5009 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005010 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005011
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005012 case CK_BitCast:
5013 if (SubExpr->getType()->isAnyPointerType() ||
5014 SubExpr->getType()->isBlockPointerType() ||
5015 SubExpr->getType()->isObjCQualifiedIdType())
5016 return EvalAddr(SubExpr, refVars, ParentDecl);
5017 else
5018 return nullptr;
5019
Eli Friedman8b9414e2012-02-23 23:04:32 +00005020 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005021 return nullptr;
Eli Friedman8b9414e2012-02-23 23:04:32 +00005022 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005023 }
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Douglas Gregor03e80032011-06-21 17:03:29 +00005025 case Stmt::MaterializeTemporaryExprClass:
5026 if (Expr *Result = EvalAddr(
5027 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005028 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005029 return Result;
5030
5031 return E;
5032
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005033 // Everything else: we simply don't reason about them.
5034 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005035 return nullptr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005036 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005037}
Mike Stump1eb44332009-09-09 15:08:12 +00005038
Ted Kremenek06de2762007-08-17 16:46:58 +00005039
5040/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5041/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005042static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5043 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005044do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005045 // We should only be called for evaluating non-pointer expressions, or
5046 // expressions with a pointer type that are not used as references but instead
5047 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00005048
Ted Kremenek06de2762007-08-17 16:46:58 +00005049 // Our "symbolic interpreter" is just a dispatch off the currently
5050 // viewed AST node. We then recursively traverse the AST by calling
5051 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00005052
5053 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00005054 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005055 case Stmt::ImplicitCastExprClass: {
5056 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00005057 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005058 E = IE->getSubExpr();
5059 continue;
5060 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005061 return nullptr;
Ted Kremenek68957a92010-08-04 20:01:07 +00005062 }
5063
John McCall80ee6e82011-11-10 05:35:25 +00005064 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005065 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005066
Douglas Gregora2813ce2009-10-23 18:54:35 +00005067 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005068 // When we hit a DeclRefExpr we are looking at code that refers to a
5069 // variable's name. If it's not a reference variable we check if it has
5070 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00005071 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005072
Stephen Hines651f13c2014-04-23 16:59:28 -07005073 // If we leave the immediate function, the lifetime isn't about to end.
5074 if (DR->refersToEnclosingLocal())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005075 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005076
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005077 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5078 // Check if it refers to itself, e.g. "int& i = i;".
5079 if (V == ParentDecl)
5080 return DR;
5081
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005082 if (V->hasLocalStorage()) {
5083 if (!V->getType()->isReferenceType())
5084 return DR;
5085
5086 // Reference variable, follow through to the expression that
5087 // it points to.
5088 if (V->hasInit()) {
5089 // Add the reference variable to the "trail".
5090 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005091 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005092 }
5093 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005094 }
Mike Stump1eb44332009-09-09 15:08:12 +00005095
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005096 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005097 }
Mike Stump1eb44332009-09-09 15:08:12 +00005098
Ted Kremenek06de2762007-08-17 16:46:58 +00005099 case Stmt::UnaryOperatorClass: {
5100 // The only unary operator that make sense to handle here
5101 // is Deref. All others don't resolve to a "name." This includes
5102 // handling all sorts of rvalues passed to a unary operator.
5103 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005104
John McCall2de56d12010-08-25 11:45:40 +00005105 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005106 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005107
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005108 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005109 }
Mike Stump1eb44332009-09-09 15:08:12 +00005110
Ted Kremenek06de2762007-08-17 16:46:58 +00005111 case Stmt::ArraySubscriptExprClass: {
5112 // Array subscripts are potential references to data on the stack. We
5113 // retrieve the DeclRefExpr* for the array variable if it indeed
5114 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005115 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005116 }
Mike Stump1eb44332009-09-09 15:08:12 +00005117
Ted Kremenek06de2762007-08-17 16:46:58 +00005118 case Stmt::ConditionalOperatorClass: {
5119 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005120 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00005121 ConditionalOperator *C = cast<ConditionalOperator>(E);
5122
Anders Carlsson39073232007-11-30 19:04:31 +00005123 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005124 if (Expr *LHSExpr = C->getLHS()) {
5125 // In C++, we can have a throw-expression, which has 'void' type.
5126 if (!LHSExpr->getType()->isVoidType())
5127 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5128 return LHS;
5129 }
5130
5131 // In C++, we can have a throw-expression, which has 'void' type.
5132 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005133 return nullptr;
Anders Carlsson39073232007-11-30 19:04:31 +00005134
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005135 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005136 }
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Ted Kremenek06de2762007-08-17 16:46:58 +00005138 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00005139 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00005140 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005141
Ted Kremenek06de2762007-08-17 16:46:58 +00005142 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00005143 if (M->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005144 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005145
5146 // Check whether the member type is itself a reference, in which case
5147 // we're not going to refer to the member, but to what the member refers to.
5148 if (M->getMemberDecl()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005149 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005150
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005151 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005152 }
Mike Stump1eb44332009-09-09 15:08:12 +00005153
Douglas Gregor03e80032011-06-21 17:03:29 +00005154 case Stmt::MaterializeTemporaryExprClass:
5155 if (Expr *Result = EvalVal(
5156 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005157 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005158 return Result;
5159
5160 return E;
5161
Ted Kremenek06de2762007-08-17 16:46:58 +00005162 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005163 // Check that we don't return or take the address of a reference to a
5164 // temporary. This is only useful in C++.
5165 if (!E->isTypeDependent() && E->isRValue())
5166 return E;
5167
5168 // Everything else: we simply don't reason about them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005169 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005170 }
Ted Kremenek68957a92010-08-04 20:01:07 +00005171} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00005172}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005173
Stephen Hines651f13c2014-04-23 16:59:28 -07005174void
5175Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5176 SourceLocation ReturnLoc,
5177 bool isObjCMethod,
5178 const AttrVec *Attrs,
5179 const FunctionDecl *FD) {
5180 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5181
5182 // Check if the return value is null but should not be.
5183 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5184 CheckNonNullExpr(*this, RetValExp))
5185 Diag(ReturnLoc, diag::warn_null_ret)
5186 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5187
5188 // C++11 [basic.stc.dynamic.allocation]p4:
5189 // If an allocation function declared with a non-throwing
5190 // exception-specification fails to allocate storage, it shall return
5191 // a null pointer. Any other allocation function that fails to allocate
5192 // storage shall indicate failure only by throwing an exception [...]
5193 if (FD) {
5194 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5195 if (Op == OO_New || Op == OO_Array_New) {
5196 const FunctionProtoType *Proto
5197 = FD->getType()->castAs<FunctionProtoType>();
5198 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5199 CheckNonNullExpr(*this, RetValExp))
5200 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5201 << FD << getLangOpts().CPlusPlus11;
5202 }
5203 }
5204}
5205
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005206//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5207
5208/// Check for comparisons of floating point operands using != and ==.
5209/// Issue a warning if these are no self-comparisons, as they are not likely
5210/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00005211void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00005212 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5213 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005214
5215 // Special case: check for x == x (which is OK).
5216 // Do not emit warnings for such cases.
5217 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5218 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5219 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00005220 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005221
5222
Ted Kremenek1b500bb2007-11-29 00:59:04 +00005223 // Special case: check for comparisons against literals that can be exactly
5224 // represented by APFloat. In such cases, do not emit a warning. This
5225 // is a heuristic: often comparison against such literals are used to
5226 // detect if a value in a variable has not changed. This clearly can
5227 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00005228 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5229 if (FLL->isExact())
5230 return;
5231 } else
5232 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5233 if (FLR->isExact())
5234 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005235
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005236 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00005237 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005238 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005240
David Blaikie980343b2012-07-16 20:47:22 +00005241 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005242 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005243 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005244
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005245 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00005246 Diag(Loc, diag::warn_floatingpoint_eq)
5247 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005248}
John McCallba26e582010-01-04 23:21:16 +00005249
John McCallf2370c92010-01-06 05:24:50 +00005250//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5251//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00005252
John McCallf2370c92010-01-06 05:24:50 +00005253namespace {
John McCallba26e582010-01-04 23:21:16 +00005254
John McCallf2370c92010-01-06 05:24:50 +00005255/// Structure recording the 'active' range of an integer-valued
5256/// expression.
5257struct IntRange {
5258 /// The number of bits active in the int.
5259 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00005260
John McCallf2370c92010-01-06 05:24:50 +00005261 /// True if the int is known not to have negative values.
5262 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00005263
John McCallf2370c92010-01-06 05:24:50 +00005264 IntRange(unsigned Width, bool NonNegative)
5265 : Width(Width), NonNegative(NonNegative)
5266 {}
John McCallba26e582010-01-04 23:21:16 +00005267
John McCall1844a6e2010-11-10 23:38:19 +00005268 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00005269 static IntRange forBoolType() {
5270 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00005271 }
5272
John McCall1844a6e2010-11-10 23:38:19 +00005273 /// Returns the range of an opaque value of the given integral type.
5274 static IntRange forValueOfType(ASTContext &C, QualType T) {
5275 return forValueOfCanonicalType(C,
5276 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00005277 }
5278
John McCall1844a6e2010-11-10 23:38:19 +00005279 /// Returns the range of an opaque value of a canonical integral type.
5280 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00005281 assert(T->isCanonicalUnqualified());
5282
5283 if (const VectorType *VT = dyn_cast<VectorType>(T))
5284 T = VT->getElementType().getTypePtr();
5285 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5286 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005287 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5288 T = AT->getValueType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00005289
David Majnemerf9eaf982013-06-07 22:07:20 +00005290 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00005291 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00005292 EnumDecl *Enum = ET->getDecl();
5293 if (!Enum->isCompleteDefinition())
5294 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00005295
David Majnemerf9eaf982013-06-07 22:07:20 +00005296 unsigned NumPositive = Enum->getNumPositiveBits();
5297 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00005298
David Majnemerf9eaf982013-06-07 22:07:20 +00005299 if (NumNegative == 0)
5300 return IntRange(NumPositive, true/*NonNegative*/);
5301 else
5302 return IntRange(std::max(NumPositive + 1, NumNegative),
5303 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00005304 }
John McCallf2370c92010-01-06 05:24:50 +00005305
5306 const BuiltinType *BT = cast<BuiltinType>(T);
5307 assert(BT->isInteger());
5308
5309 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5310 }
5311
John McCall1844a6e2010-11-10 23:38:19 +00005312 /// Returns the "target" range of a canonical integral type, i.e.
5313 /// the range of values expressible in the type.
5314 ///
5315 /// This matches forValueOfCanonicalType except that enums have the
5316 /// full range of their type, not the range of their enumerators.
5317 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5318 assert(T->isCanonicalUnqualified());
5319
5320 if (const VectorType *VT = dyn_cast<VectorType>(T))
5321 T = VT->getElementType().getTypePtr();
5322 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5323 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005324 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5325 T = AT->getValueType().getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005326 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00005327 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005328
5329 const BuiltinType *BT = cast<BuiltinType>(T);
5330 assert(BT->isInteger());
5331
5332 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5333 }
5334
5335 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005336 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00005337 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00005338 L.NonNegative && R.NonNegative);
5339 }
5340
John McCall1844a6e2010-11-10 23:38:19 +00005341 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005342 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00005343 return IntRange(std::min(L.Width, R.Width),
5344 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00005345 }
5346};
5347
Ted Kremenek0692a192012-01-31 05:37:37 +00005348static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5349 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005350 if (value.isSigned() && value.isNegative())
5351 return IntRange(value.getMinSignedBits(), false);
5352
5353 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00005354 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005355
5356 // isNonNegative() just checks the sign bit without considering
5357 // signedness.
5358 return IntRange(value.getActiveBits(), true);
5359}
5360
Ted Kremenek0692a192012-01-31 05:37:37 +00005361static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5362 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005363 if (result.isInt())
5364 return GetValueRange(C, result.getInt(), MaxWidth);
5365
5366 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00005367 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5368 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5369 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5370 R = IntRange::join(R, El);
5371 }
John McCallf2370c92010-01-06 05:24:50 +00005372 return R;
5373 }
5374
5375 if (result.isComplexInt()) {
5376 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5377 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5378 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00005379 }
5380
5381 // This can happen with lossless casts to intptr_t of "based" lvalues.
5382 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00005383 // FIXME: The only reason we need to pass the type in here is to get
5384 // the sign right on this one case. It would be nice if APValue
5385 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00005386 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005387 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00005388}
John McCallf2370c92010-01-06 05:24:50 +00005389
Eli Friedman09bddcf2013-07-08 20:20:06 +00005390static QualType GetExprType(Expr *E) {
5391 QualType Ty = E->getType();
5392 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5393 Ty = AtomicRHS->getValueType();
5394 return Ty;
5395}
5396
John McCallf2370c92010-01-06 05:24:50 +00005397/// Pseudo-evaluate the given integer expression, estimating the
5398/// range of values it might take.
5399///
5400/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00005401static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005402 E = E->IgnoreParens();
5403
5404 // Try a full evaluation first.
5405 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005406 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00005407 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005408
5409 // I think we only want to look through implicit casts here; if the
5410 // user has an explicit widening cast, we should treat the value as
5411 // being of the new, wider type.
5412 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00005413 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00005414 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5415
Eli Friedman09bddcf2013-07-08 20:20:06 +00005416 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00005417
John McCall2de56d12010-08-25 11:45:40 +00005418 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00005419
John McCallf2370c92010-01-06 05:24:50 +00005420 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00005421 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00005422 return OutputTypeRange;
5423
5424 IntRange SubRange
5425 = GetExprRange(C, CE->getSubExpr(),
5426 std::min(MaxWidth, OutputTypeRange.Width));
5427
5428 // Bail out if the subexpr's range is as wide as the cast type.
5429 if (SubRange.Width >= OutputTypeRange.Width)
5430 return OutputTypeRange;
5431
5432 // Otherwise, we take the smaller width, and we're non-negative if
5433 // either the output type or the subexpr is.
5434 return IntRange(SubRange.Width,
5435 SubRange.NonNegative || OutputTypeRange.NonNegative);
5436 }
5437
5438 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5439 // If we can fold the condition, just take that operand.
5440 bool CondResult;
5441 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5442 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5443 : CO->getFalseExpr(),
5444 MaxWidth);
5445
5446 // Otherwise, conservatively merge.
5447 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5448 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5449 return IntRange::join(L, R);
5450 }
5451
5452 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5453 switch (BO->getOpcode()) {
5454
5455 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005456 case BO_LAnd:
5457 case BO_LOr:
5458 case BO_LT:
5459 case BO_GT:
5460 case BO_LE:
5461 case BO_GE:
5462 case BO_EQ:
5463 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005464 return IntRange::forBoolType();
5465
John McCall862ff872011-07-13 06:35:24 +00005466 // The type of the assignments is the type of the LHS, so the RHS
5467 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005468 case BO_MulAssign:
5469 case BO_DivAssign:
5470 case BO_RemAssign:
5471 case BO_AddAssign:
5472 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005473 case BO_XorAssign:
5474 case BO_OrAssign:
5475 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005476 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005477
John McCall862ff872011-07-13 06:35:24 +00005478 // Simple assignments just pass through the RHS, which will have
5479 // been coerced to the LHS type.
5480 case BO_Assign:
5481 // TODO: bitfields?
5482 return GetExprRange(C, BO->getRHS(), MaxWidth);
5483
John McCallf2370c92010-01-06 05:24:50 +00005484 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005485 case BO_PtrMemD:
5486 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005487 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005488
John McCall60fad452010-01-06 22:07:33 +00005489 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005490 case BO_And:
5491 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005492 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5493 GetExprRange(C, BO->getRHS(), MaxWidth));
5494
John McCallf2370c92010-01-06 05:24:50 +00005495 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005496 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005497 // ...except that we want to treat '1 << (blah)' as logically
5498 // positive. It's an important idiom.
5499 if (IntegerLiteral *I
5500 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5501 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005502 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005503 return IntRange(R.Width, /*NonNegative*/ true);
5504 }
5505 }
5506 // fallthrough
5507
John McCall2de56d12010-08-25 11:45:40 +00005508 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005509 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005510
John McCall60fad452010-01-06 22:07:33 +00005511 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005512 case BO_Shr:
5513 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005514 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5515
5516 // If the shift amount is a positive constant, drop the width by
5517 // that much.
5518 llvm::APSInt shift;
5519 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5520 shift.isNonNegative()) {
5521 unsigned zext = shift.getZExtValue();
5522 if (zext >= L.Width)
5523 L.Width = (L.NonNegative ? 0 : 1);
5524 else
5525 L.Width -= zext;
5526 }
5527
5528 return L;
5529 }
5530
5531 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005532 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005533 return GetExprRange(C, BO->getRHS(), MaxWidth);
5534
John McCall60fad452010-01-06 22:07:33 +00005535 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005536 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005537 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005538 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005539 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005540
John McCall00fe7612011-07-14 22:39:48 +00005541 // The width of a division result is mostly determined by the size
5542 // of the LHS.
5543 case BO_Div: {
5544 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005545 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005546 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5547
5548 // If the divisor is constant, use that.
5549 llvm::APSInt divisor;
5550 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5551 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5552 if (log2 >= L.Width)
5553 L.Width = (L.NonNegative ? 0 : 1);
5554 else
5555 L.Width = std::min(L.Width - log2, MaxWidth);
5556 return L;
5557 }
5558
5559 // Otherwise, just use the LHS's width.
5560 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5561 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5562 }
5563
5564 // The result of a remainder can't be larger than the result of
5565 // either side.
5566 case BO_Rem: {
5567 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005568 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005569 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5570 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5571
5572 IntRange meet = IntRange::meet(L, R);
5573 meet.Width = std::min(meet.Width, MaxWidth);
5574 return meet;
5575 }
5576
5577 // The default behavior is okay for these.
5578 case BO_Mul:
5579 case BO_Add:
5580 case BO_Xor:
5581 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005582 break;
5583 }
5584
John McCall00fe7612011-07-14 22:39:48 +00005585 // The default case is to treat the operation as if it were closed
5586 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005587 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5588 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5589 return IntRange::join(L, R);
5590 }
5591
5592 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5593 switch (UO->getOpcode()) {
5594 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005595 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005596 return IntRange::forBoolType();
5597
5598 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005599 case UO_Deref:
5600 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005601 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005602
5603 default:
5604 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5605 }
5606 }
5607
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005608 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5609 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5610
John McCall993f43f2013-05-06 21:39:12 +00005611 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005612 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005613 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005614
Eli Friedman09bddcf2013-07-08 20:20:06 +00005615 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005616}
John McCall51313c32010-01-04 23:31:57 +00005617
Ted Kremenek0692a192012-01-31 05:37:37 +00005618static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005619 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005620}
5621
John McCall51313c32010-01-04 23:31:57 +00005622/// Checks whether the given value, which currently has the given
5623/// source semantics, has the same value when coerced through the
5624/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005625static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5626 const llvm::fltSemantics &Src,
5627 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005628 llvm::APFloat truncated = value;
5629
5630 bool ignored;
5631 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5632 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5633
5634 return truncated.bitwiseIsEqual(value);
5635}
5636
5637/// Checks whether the given value, which currently has the given
5638/// source semantics, has the same value when coerced through the
5639/// target semantics.
5640///
5641/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005642static bool IsSameFloatAfterCast(const APValue &value,
5643 const llvm::fltSemantics &Src,
5644 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005645 if (value.isFloat())
5646 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5647
5648 if (value.isVector()) {
5649 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5650 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5651 return false;
5652 return true;
5653 }
5654
5655 assert(value.isComplexFloat());
5656 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5657 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5658}
5659
Ted Kremenek0692a192012-01-31 05:37:37 +00005660static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005661
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005662static bool IsZero(Sema &S, Expr *E) {
5663 // Suppress cases where we are comparing against an enum constant.
5664 if (const DeclRefExpr *DR =
5665 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5666 if (isa<EnumConstantDecl>(DR->getDecl()))
5667 return false;
5668
5669 // Suppress cases where the '0' value is expanded from a macro.
5670 if (E->getLocStart().isMacroID())
5671 return false;
5672
John McCall323ed742010-05-06 08:58:33 +00005673 llvm::APSInt Value;
5674 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5675}
5676
John McCall372e1032010-10-06 00:25:24 +00005677static bool HasEnumType(Expr *E) {
5678 // Strip off implicit integral promotions.
5679 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005680 if (ICE->getCastKind() != CK_IntegralCast &&
5681 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00005682 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005683 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00005684 }
5685
5686 return E->getType()->isEnumeralType();
5687}
5688
Ted Kremenek0692a192012-01-31 05:37:37 +00005689static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00005690 // Disable warning in template instantiations.
5691 if (!S.ActiveTemplateInstantiations.empty())
5692 return;
5693
John McCall2de56d12010-08-25 11:45:40 +00005694 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00005695 if (E->isValueDependent())
5696 return;
5697
John McCall2de56d12010-08-25 11:45:40 +00005698 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005699 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005700 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005701 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005702 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005703 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005704 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005705 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005706 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005707 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005708 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005709 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005710 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005711 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005712 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005713 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5714 }
5715}
5716
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005717static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005718 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005719 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005720 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00005721 // Disable warning in template instantiations.
5722 if (!S.ActiveTemplateInstantiations.empty())
5723 return;
5724
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005725 // TODO: Investigate using GetExprRange() to get tighter bounds
5726 // on the bit ranges.
5727 QualType OtherT = Other->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08005728 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5729 OtherT = AT->getValueType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005730 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5731 unsigned OtherWidth = OtherRange.Width;
5732
5733 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5734
Richard Trieu526e6272012-11-14 22:50:24 +00005735 // 0 values are handled later by CheckTrivialUnsignedComparison().
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005736 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu526e6272012-11-14 22:50:24 +00005737 return;
5738
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005739 BinaryOperatorKind op = E->getOpcode();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005740 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00005741
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005742 // Used for diagnostic printout.
5743 enum {
5744 LiteralConstant = 0,
5745 CXXBoolLiteralTrue,
5746 CXXBoolLiteralFalse
5747 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00005748
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005749 if (!OtherIsBooleanType) {
5750 QualType ConstantT = Constant->getType();
5751 QualType CommonT = E->getLHS()->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00005752
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005753 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5754 return;
5755 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5756 "comparison with non-integer type");
5757
5758 bool ConstantSigned = ConstantT->isSignedIntegerType();
5759 bool CommonSigned = CommonT->isSignedIntegerType();
5760
5761 bool EqualityOnly = false;
5762
5763 if (CommonSigned) {
5764 // The common type is signed, therefore no signed to unsigned conversion.
5765 if (!OtherRange.NonNegative) {
5766 // Check that the constant is representable in type OtherT.
5767 if (ConstantSigned) {
5768 if (OtherWidth >= Value.getMinSignedBits())
5769 return;
5770 } else { // !ConstantSigned
5771 if (OtherWidth >= Value.getActiveBits() + 1)
5772 return;
5773 }
5774 } else { // !OtherSigned
5775 // Check that the constant is representable in type OtherT.
5776 // Negative values are out of range.
5777 if (ConstantSigned) {
5778 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5779 return;
5780 } else { // !ConstantSigned
5781 if (OtherWidth >= Value.getActiveBits())
5782 return;
5783 }
Richard Trieu526e6272012-11-14 22:50:24 +00005784 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005785 } else { // !CommonSigned
5786 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00005787 if (OtherWidth >= Value.getActiveBits())
5788 return;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005789 } else { // OtherSigned
5790 assert(!ConstantSigned &&
5791 "Two signed types converted to unsigned types.");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005792 // Check to see if the constant is representable in OtherT.
5793 if (OtherWidth > Value.getActiveBits())
5794 return;
5795 // Check to see if the constant is equivalent to a negative value
5796 // cast to CommonT.
5797 if (S.Context.getIntWidth(ConstantT) ==
5798 S.Context.getIntWidth(CommonT) &&
5799 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5800 return;
5801 // The constant value rests between values that OtherT can represent
5802 // after conversion. Relational comparison still works, but equality
5803 // comparisons will be tautological.
5804 EqualityOnly = true;
Richard Trieu526e6272012-11-14 22:50:24 +00005805 }
5806 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005807
5808 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5809
5810 if (op == BO_EQ || op == BO_NE) {
5811 IsTrue = op == BO_NE;
5812 } else if (EqualityOnly) {
5813 return;
5814 } else if (RhsConstant) {
5815 if (op == BO_GT || op == BO_GE)
5816 IsTrue = !PositiveConstant;
5817 else // op == BO_LT || op == BO_LE
5818 IsTrue = PositiveConstant;
5819 } else {
5820 if (op == BO_LT || op == BO_LE)
5821 IsTrue = !PositiveConstant;
5822 else // op == BO_GT || op == BO_GE
5823 IsTrue = PositiveConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00005824 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005825 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005826 // Other isKnownToHaveBooleanValue
5827 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5828 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5829 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5830
5831 static const struct LinkedConditions {
5832 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5833 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5834 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5835 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5836 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5837 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5838
5839 } TruthTable = {
5840 // Constant on LHS. | Constant on RHS. |
5841 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5842 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5843 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5844 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5845 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5846 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5847 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5848 };
5849
5850 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5851
5852 enum ConstantValue ConstVal = Zero;
5853 if (Value.isUnsigned() || Value.isNonNegative()) {
5854 if (Value == 0) {
5855 LiteralOrBoolConstant =
5856 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5857 ConstVal = Zero;
5858 } else if (Value == 1) {
5859 LiteralOrBoolConstant =
5860 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5861 ConstVal = One;
5862 } else {
5863 LiteralOrBoolConstant = LiteralConstant;
5864 ConstVal = GT_One;
5865 }
5866 } else {
5867 ConstVal = LT_Zero;
5868 }
5869
5870 CompareBoolWithConstantResult CmpRes;
5871
5872 switch (op) {
5873 case BO_LT:
5874 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5875 break;
5876 case BO_GT:
5877 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5878 break;
5879 case BO_LE:
5880 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5881 break;
5882 case BO_GE:
5883 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5884 break;
5885 case BO_EQ:
5886 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5887 break;
5888 case BO_NE:
5889 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5890 break;
5891 default:
5892 CmpRes = Unkwn;
5893 break;
5894 }
5895
5896 if (CmpRes == AFals) {
5897 IsTrue = false;
5898 } else if (CmpRes == ATrue) {
5899 IsTrue = true;
5900 } else {
5901 return;
5902 }
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005903 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005904
5905 // If this is a comparison to an enum constant, include that
5906 // constant in the diagnostic.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005907 const EnumConstantDecl *ED = nullptr;
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005908 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5909 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5910
5911 SmallString<64> PrettySourceValue;
5912 llvm::raw_svector_ostream OS(PrettySourceValue);
5913 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00005914 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005915 else
5916 OS << Value;
5917
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005918 S.DiagRuntimeBehavior(
5919 E->getOperatorLoc(), E,
5920 S.PDiag(diag::warn_out_of_range_compare)
5921 << OS.str() << LiteralOrBoolConstant
5922 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5923 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005924}
5925
John McCall323ed742010-05-06 08:58:33 +00005926/// Analyze the operands of the given comparison. Implements the
5927/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00005928static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00005929 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5930 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00005931}
John McCall51313c32010-01-04 23:31:57 +00005932
John McCallba26e582010-01-04 23:21:16 +00005933/// \brief Implements -Wsign-compare.
5934///
Richard Trieudd225092011-09-15 21:56:47 +00005935/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00005936static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00005937 // The type the comparison is being performed in.
5938 QualType T = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08005939
5940 // Only analyze comparison operators where both sides have been converted to
5941 // the same type.
5942 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
5943 return AnalyzeImpConvsInComparison(S, E);
5944
5945 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00005946 if (E->isValueDependent())
5947 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005948
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005949 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5950 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005951
5952 bool IsComparisonConstant = false;
5953
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005954 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005955 // of 'true' or 'false'.
5956 if (T->isIntegralType(S.Context)) {
5957 llvm::APSInt RHSValue;
5958 bool IsRHSIntegralLiteral =
5959 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5960 llvm::APSInt LHSValue;
5961 bool IsLHSIntegralLiteral =
5962 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5963 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5964 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5965 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5966 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5967 else
5968 IsComparisonConstant =
5969 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005970 } else if (!T->hasUnsignedIntegerRepresentation())
5971 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005972
John McCall323ed742010-05-06 08:58:33 +00005973 // We don't do anything special if this isn't an unsigned integral
5974 // comparison: we're only interested in integral comparisons, and
5975 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00005976 //
5977 // We also don't care about value-dependent expressions or expressions
5978 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005979 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00005980 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005981
John McCall323ed742010-05-06 08:58:33 +00005982 // Check to see if one of the (unmodified) operands is of different
5983 // signedness.
5984 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00005985 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5986 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00005987 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00005988 signedOperand = LHS;
5989 unsignedOperand = RHS;
5990 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5991 signedOperand = RHS;
5992 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00005993 } else {
John McCall323ed742010-05-06 08:58:33 +00005994 CheckTrivialUnsignedComparison(S, E);
5995 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005996 }
5997
John McCall323ed742010-05-06 08:58:33 +00005998 // Otherwise, calculate the effective range of the signed operand.
5999 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00006000
John McCall323ed742010-05-06 08:58:33 +00006001 // Go ahead and analyze implicit conversions in the operands. Note
6002 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00006003 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6004 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00006005
John McCall323ed742010-05-06 08:58:33 +00006006 // If the signed range is non-negative, -Wsign-compare won't fire,
6007 // but we should still check for comparisons which are always true
6008 // or false.
6009 if (signedRange.NonNegative)
6010 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006011
6012 // For (in)equality comparisons, if the unsigned operand is a
6013 // constant which cannot collide with a overflowed signed operand,
6014 // then reinterpreting the signed operand as unsigned will not
6015 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00006016 if (E->isEqualityOp()) {
6017 unsigned comparisonWidth = S.Context.getIntWidth(T);
6018 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00006019
John McCall323ed742010-05-06 08:58:33 +00006020 // We should never be unable to prove that the unsigned operand is
6021 // non-negative.
6022 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6023
6024 if (unsignedRange.Width < comparisonWidth)
6025 return;
6026 }
6027
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00006028 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6029 S.PDiag(diag::warn_mixed_sign_comparison)
6030 << LHS->getType() << RHS->getType()
6031 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00006032}
6033
John McCall15d7d122010-11-11 03:21:53 +00006034/// Analyzes an attempt to assign the given value to a bitfield.
6035///
6036/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00006037static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6038 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00006039 assert(Bitfield->isBitField());
6040 if (Bitfield->isInvalidDecl())
6041 return false;
6042
John McCall91b60142010-11-11 05:33:51 +00006043 // White-list bool bitfields.
6044 if (Bitfield->getType()->isBooleanType())
6045 return false;
6046
Douglas Gregor46ff3032011-02-04 13:09:01 +00006047 // Ignore value- or type-dependent expressions.
6048 if (Bitfield->getBitWidth()->isValueDependent() ||
6049 Bitfield->getBitWidth()->isTypeDependent() ||
6050 Init->isValueDependent() ||
6051 Init->isTypeDependent())
6052 return false;
6053
John McCall15d7d122010-11-11 03:21:53 +00006054 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6055
Richard Smith80d4b552011-12-28 19:48:30 +00006056 llvm::APSInt Value;
6057 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00006058 return false;
6059
John McCall15d7d122010-11-11 03:21:53 +00006060 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006061 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00006062
6063 if (OriginalWidth <= FieldWidth)
6064 return false;
6065
Eli Friedman3a643af2012-01-26 23:11:39 +00006066 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006067 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00006068 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00006069
Eli Friedman3a643af2012-01-26 23:11:39 +00006070 // Check whether the stored value is equal to the original value.
6071 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00006072 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00006073 return false;
6074
Eli Friedman3a643af2012-01-26 23:11:39 +00006075 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00006076 // therefore don't strictly fit into a signed bitfield of width 1.
6077 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00006078 return false;
6079
John McCall15d7d122010-11-11 03:21:53 +00006080 std::string PrettyValue = Value.toString(10);
6081 std::string PrettyTrunc = TruncatedValue.toString(10);
6082
6083 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6084 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6085 << Init->getSourceRange();
6086
6087 return true;
6088}
6089
John McCallbeb22aa2010-11-09 23:24:47 +00006090/// Analyze the given simple or compound assignment for warning-worthy
6091/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00006092static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00006093 // Just recurse on the LHS.
6094 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6095
6096 // We want to recurse on the RHS as normal unless we're assigning to
6097 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00006098 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006099 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00006100 E->getOperatorLoc())) {
6101 // Recurse, ignoring any implicit conversions on the RHS.
6102 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6103 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00006104 }
6105 }
6106
6107 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6108}
6109
John McCall51313c32010-01-04 23:31:57 +00006110/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006111static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006112 SourceLocation CContext, unsigned diag,
6113 bool pruneControlFlow = false) {
6114 if (pruneControlFlow) {
6115 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6116 S.PDiag(diag)
6117 << SourceType << T << E->getSourceRange()
6118 << SourceRange(CContext));
6119 return;
6120 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006121 S.Diag(E->getExprLoc(), diag)
6122 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6123}
6124
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006125/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006126static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006127 SourceLocation CContext, unsigned diag,
6128 bool pruneControlFlow = false) {
6129 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006130}
6131
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006132/// Diagnose an implicit cast from a literal expression. Does not warn when the
6133/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006134void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6135 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006136 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006137 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006138 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00006139 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6140 T->hasUnsignedIntegerRepresentation());
6141 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00006142 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006143 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00006144 return;
6145
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006146 // FIXME: Force the precision of the source value down so we don't print
6147 // digits which are usually useless (we don't really care here if we
6148 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6149 // would automatically print the shortest representation, but it's a bit
6150 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00006151 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006152 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6153 precision = (precision * 59 + 195) / 196;
6154 Value.toString(PrettySourceValue, precision);
6155
David Blaikiede7e7b82012-05-15 17:18:27 +00006156 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00006157 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6158 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6159 else
David Blaikiede7e7b82012-05-15 17:18:27 +00006160 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00006161
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006162 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00006163 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6164 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00006165}
6166
John McCall091f23f2010-11-09 22:22:12 +00006167std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6168 if (!Range.Width) return "0";
6169
6170 llvm::APSInt ValueInRange = Value;
6171 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00006172 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00006173 return ValueInRange.toString(10);
6174}
6175
Hans Wennborg88617a22012-08-28 15:44:30 +00006176static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6177 if (!isa<ImplicitCastExpr>(Ex))
6178 return false;
6179
6180 Expr *InnerE = Ex->IgnoreParenImpCasts();
6181 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6182 const Type *Source =
6183 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6184 if (Target->isDependentType())
6185 return false;
6186
6187 const BuiltinType *FloatCandidateBT =
6188 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6189 const Type *BoolCandidateType = ToBool ? Target : Source;
6190
6191 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6192 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6193}
6194
6195void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6196 SourceLocation CC) {
6197 unsigned NumArgs = TheCall->getNumArgs();
6198 for (unsigned i = 0; i < NumArgs; ++i) {
6199 Expr *CurrA = TheCall->getArg(i);
6200 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6201 continue;
6202
6203 bool IsSwapped = ((i > 0) &&
6204 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6205 IsSwapped |= ((i < (NumArgs - 1)) &&
6206 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6207 if (IsSwapped) {
6208 // Warn on this floating-point to bool conversion.
6209 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6210 CurrA->getType(), CC,
6211 diag::warn_impcast_floating_point_to_bool);
6212 }
6213 }
6214}
6215
Stephen Hines176edba2014-12-01 14:53:08 -08006216static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6217 SourceLocation CC) {
6218 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6219 E->getExprLoc()))
6220 return;
6221
6222 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6223 const Expr::NullPointerConstantKind NullKind =
6224 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6225 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6226 return;
6227
6228 // Return if target type is a safe conversion.
6229 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6230 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6231 return;
6232
6233 SourceLocation Loc = E->getSourceRange().getBegin();
6234
6235 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6236 if (NullKind == Expr::NPCK_GNUNull) {
6237 if (Loc.isMacroID())
6238 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6239 }
6240
6241 // Only warn if the null and context location are in the same macro expansion.
6242 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6243 return;
6244
6245 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6246 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6247 << FixItHint::CreateReplacement(Loc,
6248 S.getFixItZeroLiteralForType(T, Loc));
6249}
6250
John McCall323ed742010-05-06 08:58:33 +00006251void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006252 SourceLocation CC, bool *ICContext = nullptr) {
John McCall323ed742010-05-06 08:58:33 +00006253 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00006254
John McCall323ed742010-05-06 08:58:33 +00006255 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6256 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6257 if (Source == Target) return;
6258 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00006259
Chandler Carruth108f7562011-07-26 05:40:03 +00006260 // If the conversion context location is invalid don't complain. We also
6261 // don't want to emit a warning if the issue occurs from the expansion of
6262 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6263 // delay this check as long as possible. Once we detect we are in that
6264 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00006265 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00006266 return;
6267
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006268 // Diagnose implicit casts to bool.
6269 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6270 if (isa<StringLiteral>(E))
6271 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07006272 // and expressions, for instance, assert(0 && "error here"), are
6273 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006274 return DiagnoseImpCast(S, E, T, CC,
6275 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07006276 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6277 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6278 // This covers the literal expressions that evaluate to Objective-C
6279 // objects.
6280 return DiagnoseImpCast(S, E, T, CC,
6281 diag::warn_impcast_objective_c_literal_to_bool);
6282 }
6283 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6284 // Warn on pointer to bool conversion that is always true.
6285 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6286 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00006287 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006288 }
John McCall51313c32010-01-04 23:31:57 +00006289
6290 // Strip vector types.
6291 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006292 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006293 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006294 return;
John McCallb4eb64d2010-10-08 02:01:28 +00006295 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006296 }
Chris Lattnerb792b302011-06-14 04:51:15 +00006297
6298 // If the vector cast is cast between two vectors of the same size, it is
6299 // a bitcast, not a conversion.
6300 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6301 return;
John McCall51313c32010-01-04 23:31:57 +00006302
6303 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6304 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6305 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006306 if (auto VecTy = dyn_cast<VectorType>(Target))
6307 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00006308
6309 // Strip complex types.
6310 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006311 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006312 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006313 return;
6314
John McCallb4eb64d2010-10-08 02:01:28 +00006315 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006316 }
John McCall51313c32010-01-04 23:31:57 +00006317
6318 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6319 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6320 }
6321
6322 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6323 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6324
6325 // If the source is floating point...
6326 if (SourceBT && SourceBT->isFloatingPoint()) {
6327 // ...and the target is floating point...
6328 if (TargetBT && TargetBT->isFloatingPoint()) {
6329 // ...then warn if we're dropping FP rank.
6330
6331 // Builtin FP kinds are ordered by increasing FP rank.
6332 if (SourceBT->getKind() > TargetBT->getKind()) {
6333 // Don't warn about float constants that are precisely
6334 // representable in the target type.
6335 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00006336 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00006337 // Value might be a float, a float vector, or a float complex.
6338 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00006339 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6340 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00006341 return;
6342 }
6343
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006344 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006345 return;
6346
John McCallb4eb64d2010-10-08 02:01:28 +00006347 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00006348 }
6349 return;
6350 }
6351
Ted Kremenekef9ff882011-03-10 20:03:42 +00006352 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00006353 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006354 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006355 return;
6356
Chandler Carrutha5b93322011-02-17 11:05:49 +00006357 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00006358 // We also want to warn on, e.g., "int i = -1.234"
6359 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6360 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6361 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6362
Chandler Carruthf65076e2011-04-10 08:36:24 +00006363 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6364 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00006365 } else {
6366 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6367 }
6368 }
John McCall51313c32010-01-04 23:31:57 +00006369
Hans Wennborg88617a22012-08-28 15:44:30 +00006370 // If the target is bool, warn if expr is a function or method call.
6371 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6372 isa<CallExpr>(E)) {
6373 // Check last argument of function call to see if it is an
6374 // implicit cast from a type matching the type the result
6375 // is being cast to.
6376 CallExpr *CEx = cast<CallExpr>(E);
6377 unsigned NumArgs = CEx->getNumArgs();
6378 if (NumArgs > 0) {
6379 Expr *LastA = CEx->getArg(NumArgs - 1);
6380 Expr *InnerE = LastA->IgnoreParenImpCasts();
6381 const Type *InnerType =
6382 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6383 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6384 // Warn on this floating-point to bool conversion
6385 DiagnoseImpCast(S, E, T, CC,
6386 diag::warn_impcast_floating_point_to_bool);
6387 }
6388 }
6389 }
John McCall51313c32010-01-04 23:31:57 +00006390 return;
6391 }
6392
Stephen Hines176edba2014-12-01 14:53:08 -08006393 DiagnoseNullConversion(S, E, T, CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00006394
David Blaikieb26331b2012-06-19 21:19:06 +00006395 if (!Source->isIntegerType() || !Target->isIntegerType())
6396 return;
6397
David Blaikiebe0ee872012-05-15 16:56:36 +00006398 // TODO: remove this early return once the false positives for constant->bool
6399 // in templates, macros, etc, are reduced or removed.
6400 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6401 return;
6402
John McCall323ed742010-05-06 08:58:33 +00006403 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00006404 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00006405
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006406 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00006407 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006408 // TODO: this should happen for bitfield stores, too.
6409 llvm::APSInt Value(32);
6410 if (E->isIntegerConstantExpr(Value, S.Context)) {
6411 if (S.SourceMgr.isInSystemMacro(CC))
6412 return;
6413
John McCall091f23f2010-11-09 22:22:12 +00006414 std::string PrettySourceValue = Value.toString(10);
6415 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006416
Ted Kremenek5e745da2011-10-22 02:37:33 +00006417 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6418 S.PDiag(diag::warn_impcast_integer_precision_constant)
6419 << PrettySourceValue << PrettyTargetValue
6420 << E->getType() << T << E->getSourceRange()
6421 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00006422 return;
6423 }
6424
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006425 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6426 if (S.SourceMgr.isInSystemMacro(CC))
6427 return;
6428
David Blaikie37050842012-04-12 22:40:54 +00006429 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00006430 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6431 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00006432 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00006433 }
6434
6435 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6436 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6437 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006438
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006439 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006440 return;
6441
John McCall323ed742010-05-06 08:58:33 +00006442 unsigned DiagID = diag::warn_impcast_integer_sign;
6443
6444 // Traditionally, gcc has warned about this under -Wsign-compare.
6445 // We also want to warn about it in -Wconversion.
6446 // So if -Wconversion is off, use a completely identical diagnostic
6447 // in the sign-compare group.
6448 // The conditional-checking code will
6449 if (ICContext) {
6450 DiagID = diag::warn_impcast_integer_sign_conditional;
6451 *ICContext = true;
6452 }
6453
John McCallb4eb64d2010-10-08 02:01:28 +00006454 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00006455 }
6456
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006457 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006458 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6459 // type, to give us better diagnostics.
6460 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00006461 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6463 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6464 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6465 SourceType = S.Context.getTypeDeclType(Enum);
6466 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6467 }
6468 }
6469
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006470 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6471 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00006472 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6473 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00006474 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006475 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006476 return;
6477
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006478 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006479 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006480 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006481
John McCall51313c32010-01-04 23:31:57 +00006482 return;
6483}
6484
David Blaikie9fb1ac52012-05-15 21:57:38 +00006485void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6486 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00006487
6488void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00006489 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00006490 E = E->IgnoreParenImpCasts();
6491
6492 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00006493 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00006494
John McCallb4eb64d2010-10-08 02:01:28 +00006495 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006496 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006497 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00006498 return;
6499}
6500
David Blaikie9fb1ac52012-05-15 21:57:38 +00006501void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6502 SourceLocation CC, QualType T) {
Stephen Hines176edba2014-12-01 14:53:08 -08006503 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCall323ed742010-05-06 08:58:33 +00006504
6505 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00006506 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6507 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006508
6509 // If -Wconversion would have warned about either of the candidates
6510 // for a signedness conversion to the context type...
6511 if (!Suspicious) return;
6512
6513 // ...but it's currently ignored...
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006514 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00006515 return;
6516
John McCall323ed742010-05-06 08:58:33 +00006517 // ...then check whether it would have warned about either of the
6518 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006519 if (E->getType() == T) return;
6520
6521 Suspicious = false;
6522 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6523 E->getType(), CC, &Suspicious);
6524 if (!Suspicious)
6525 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006526 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006527}
6528
Stephen Hines176edba2014-12-01 14:53:08 -08006529/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6530/// Input argument E is a logical expression.
6531static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6532 if (S.getLangOpts().Bool)
6533 return;
6534 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6535}
6536
John McCall323ed742010-05-06 08:58:33 +00006537/// AnalyzeImplicitConversions - Find and report any interesting
6538/// implicit conversions in the given expression. There are a couple
6539/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006540void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006541 QualType T = OrigE->getType();
6542 Expr *E = OrigE->IgnoreParenImpCasts();
6543
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006544 if (E->isTypeDependent() || E->isValueDependent())
6545 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006546
John McCall323ed742010-05-06 08:58:33 +00006547 // For conditional operators, we analyze the arguments as if they
6548 // were being fed directly into the output.
6549 if (isa<ConditionalOperator>(E)) {
6550 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006551 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006552 return;
6553 }
6554
Hans Wennborg88617a22012-08-28 15:44:30 +00006555 // Check implicit argument conversions for function calls.
6556 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6557 CheckImplicitArgumentConversions(S, Call, CC);
6558
John McCall323ed742010-05-06 08:58:33 +00006559 // Go ahead and check any implicit conversions we might have skipped.
6560 // The non-canonical typecheck is just an optimization;
6561 // CheckImplicitConversion will filter out dead implicit conversions.
6562 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006563 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006564
6565 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006566
6567 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006568 if (POE->getResultExpr())
6569 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006570 }
6571
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006572 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6573 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6574
John McCall323ed742010-05-06 08:58:33 +00006575 // Skip past explicit casts.
6576 if (isa<ExplicitCastExpr>(E)) {
6577 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006578 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006579 }
6580
John McCallbeb22aa2010-11-09 23:24:47 +00006581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6582 // Do a somewhat different check with comparison operators.
6583 if (BO->isComparisonOp())
6584 return AnalyzeComparison(S, BO);
6585
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006586 // And with simple assignments.
6587 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006588 return AnalyzeAssignment(S, BO);
6589 }
John McCall323ed742010-05-06 08:58:33 +00006590
6591 // These break the otherwise-useful invariant below. Fortunately,
6592 // we don't really need to recurse into them, because any internal
6593 // expressions should have been analyzed already when they were
6594 // built into statements.
6595 if (isa<StmtExpr>(E)) return;
6596
6597 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006598 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006599
6600 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006601 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006602 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006603 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006604 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006605 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006606 if (!ChildExpr)
6607 continue;
6608
Stephen Hines651f13c2014-04-23 16:59:28 -07006609 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006610 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006611 // Ignore checking string literals that are in logical and operators.
6612 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006613 continue;
6614 AnalyzeImplicitConversions(S, ChildExpr, CC);
6615 }
Stephen Hines176edba2014-12-01 14:53:08 -08006616
6617 if (BO && BO->isLogicalOp()) {
6618 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6619 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6620 ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
6621
6622 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6623 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6624 ::CheckBoolLikeConversion(S, SubExpr, SubExpr->getExprLoc());
6625 }
6626
6627 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6628 if (U->getOpcode() == UO_LNot)
6629 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCall323ed742010-05-06 08:58:33 +00006630}
6631
6632} // end anonymous namespace
6633
Stephen Hines651f13c2014-04-23 16:59:28 -07006634enum {
6635 AddressOf,
6636 FunctionPointer,
6637 ArrayPointer
6638};
6639
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006640// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6641// Returns true when emitting a warning about taking the address of a reference.
6642static bool CheckForReference(Sema &SemaRef, const Expr *E,
6643 PartialDiagnostic PD) {
6644 E = E->IgnoreParenImpCasts();
6645
6646 const FunctionDecl *FD = nullptr;
6647
6648 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6649 if (!DRE->getDecl()->getType()->isReferenceType())
6650 return false;
6651 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6652 if (!M->getMemberDecl()->getType()->isReferenceType())
6653 return false;
6654 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6655 if (!Call->getCallReturnType()->isReferenceType())
6656 return false;
6657 FD = Call->getDirectCallee();
6658 } else {
6659 return false;
6660 }
6661
6662 SemaRef.Diag(E->getExprLoc(), PD);
6663
6664 // If possible, point to location of function.
6665 if (FD) {
6666 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6667 }
6668
6669 return true;
6670}
6671
Stephen Hines176edba2014-12-01 14:53:08 -08006672// Returns true if the SourceLocation is expanded from any macro body.
6673// Returns false if the SourceLocation is invalid, is from not in a macro
6674// expansion, or is from expanded from a top-level macro argument.
6675static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6676 if (Loc.isInvalid())
6677 return false;
6678
6679 while (Loc.isMacroID()) {
6680 if (SM.isMacroBodyExpansion(Loc))
6681 return true;
6682 Loc = SM.getImmediateMacroCallerLoc(Loc);
6683 }
6684
6685 return false;
6686}
6687
Stephen Hines651f13c2014-04-23 16:59:28 -07006688/// \brief Diagnose pointers that are always non-null.
6689/// \param E the expression containing the pointer
6690/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6691/// compared to a null pointer
6692/// \param IsEqual True when the comparison is equal to a null pointer
6693/// \param Range Extra SourceRange to highlight in the diagnostic
6694void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6695 Expr::NullPointerConstantKind NullKind,
6696 bool IsEqual, SourceRange Range) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006697 if (!E)
6698 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07006699
6700 // Don't warn inside macros.
Stephen Hines176edba2014-12-01 14:53:08 -08006701 if (E->getExprLoc().isMacroID()) {
6702 const SourceManager &SM = getSourceManager();
6703 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6704 IsInAnyMacroBody(SM, Range.getBegin()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006705 return;
Stephen Hines176edba2014-12-01 14:53:08 -08006706 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006707 E = E->IgnoreImpCasts();
6708
6709 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6710
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006711 if (isa<CXXThisExpr>(E)) {
6712 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6713 : diag::warn_this_bool_conversion;
6714 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6715 return;
6716 }
6717
Stephen Hines651f13c2014-04-23 16:59:28 -07006718 bool IsAddressOf = false;
6719
6720 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6721 if (UO->getOpcode() != UO_AddrOf)
6722 return;
6723 IsAddressOf = true;
6724 E = UO->getSubExpr();
6725 }
6726
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006727 if (IsAddressOf) {
6728 unsigned DiagID = IsCompare
6729 ? diag::warn_address_of_reference_null_compare
6730 : diag::warn_address_of_reference_bool_conversion;
6731 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6732 << IsEqual;
6733 if (CheckForReference(*this, E, PD)) {
6734 return;
6735 }
6736 }
6737
Stephen Hines651f13c2014-04-23 16:59:28 -07006738 // Expect to find a single Decl. Skip anything more complicated.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006739 ValueDecl *D = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07006740 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6741 D = R->getDecl();
6742 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6743 D = M->getMemberDecl();
6744 }
6745
6746 // Weak Decls can be null.
6747 if (!D || D->isWeak())
6748 return;
Stephen Hines176edba2014-12-01 14:53:08 -08006749
6750 // Check for parameter decl with nonnull attribute
6751 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6752 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6753 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6754 unsigned NumArgs = FD->getNumParams();
6755 llvm::SmallBitVector AttrNonNull(NumArgs);
6756 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6757 if (!NonNull->args_size()) {
6758 AttrNonNull.set(0, NumArgs);
6759 break;
6760 }
6761 for (unsigned Val : NonNull->args()) {
6762 if (Val >= NumArgs)
6763 continue;
6764 AttrNonNull.set(Val);
6765 }
6766 }
6767 if (!AttrNonNull.empty())
6768 for (unsigned i = 0; i < NumArgs; ++i)
6769 if (FD->getParamDecl(i) == PV && AttrNonNull[i]) {
6770 std::string Str;
6771 llvm::raw_string_ostream S(Str);
6772 E->printPretty(S, nullptr, getPrintingPolicy());
6773 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6774 : diag::warn_cast_nonnull_to_bool;
6775 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6776 << Range << IsEqual;
6777 return;
6778 }
6779 }
6780 }
6781
Stephen Hines651f13c2014-04-23 16:59:28 -07006782 QualType T = D->getType();
6783 const bool IsArray = T->isArrayType();
6784 const bool IsFunction = T->isFunctionType();
6785
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006786 // Address of function is used to silence the function warning.
6787 if (IsAddressOf && IsFunction) {
6788 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07006789 }
6790
6791 // Found nothing.
6792 if (!IsAddressOf && !IsFunction && !IsArray)
6793 return;
6794
6795 // Pretty print the expression for the diagnostic.
6796 std::string Str;
6797 llvm::raw_string_ostream S(Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006798 E->printPretty(S, nullptr, getPrintingPolicy());
Stephen Hines651f13c2014-04-23 16:59:28 -07006799
6800 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6801 : diag::warn_impcast_pointer_to_bool;
6802 unsigned DiagType;
6803 if (IsAddressOf)
6804 DiagType = AddressOf;
6805 else if (IsFunction)
6806 DiagType = FunctionPointer;
6807 else if (IsArray)
6808 DiagType = ArrayPointer;
6809 else
6810 llvm_unreachable("Could not determine diagnostic.");
6811 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6812 << Range << IsEqual;
6813
6814 if (!IsFunction)
6815 return;
6816
6817 // Suggest '&' to silence the function warning.
6818 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6819 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6820
6821 // Check to see if '()' fixit should be emitted.
6822 QualType ReturnType;
6823 UnresolvedSet<4> NonTemplateOverloads;
6824 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6825 if (ReturnType.isNull())
6826 return;
6827
6828 if (IsCompare) {
6829 // There are two cases here. If there is null constant, the only suggest
6830 // for a pointer return type. If the null is 0, then suggest if the return
6831 // type is a pointer or an integer type.
6832 if (!ReturnType->isPointerType()) {
6833 if (NullKind == Expr::NPCK_ZeroExpression ||
6834 NullKind == Expr::NPCK_ZeroLiteral) {
6835 if (!ReturnType->isIntegerType())
6836 return;
6837 } else {
6838 return;
6839 }
6840 }
6841 } else { // !IsCompare
6842 // For function to bool, only suggest if the function pointer has bool
6843 // return type.
6844 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6845 return;
6846 }
6847 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006848 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Stephen Hines651f13c2014-04-23 16:59:28 -07006849}
6850
6851
John McCall323ed742010-05-06 08:58:33 +00006852/// Diagnoses "dangerous" implicit conversions within the given
6853/// expression (which is a full expression). Implements -Wconversion
6854/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006855///
6856/// \param CC the "context" location of the implicit conversion, i.e.
6857/// the most location of the syntactic entity requiring the implicit
6858/// conversion
6859void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006860 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00006861 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00006862 return;
6863
6864 // Don't diagnose for value- or type-dependent expressions.
6865 if (E->isTypeDependent() || E->isValueDependent())
6866 return;
6867
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006868 // Check for array bounds violations in cases where the check isn't triggered
6869 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6870 // ArraySubscriptExpr is on the RHS of a variable initialization.
6871 CheckArrayAccess(E);
6872
John McCallb4eb64d2010-10-08 02:01:28 +00006873 // This is not the right CC for (e.g.) a variable initialization.
6874 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006875}
6876
Stephen Hines176edba2014-12-01 14:53:08 -08006877/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6878/// Input argument E is a logical expression.
6879void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6880 ::CheckBoolLikeConversion(*this, E, CC);
6881}
6882
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006883/// Diagnose when expression is an integer constant expression and its evaluation
6884/// results in integer overflow
6885void Sema::CheckForIntOverflow (Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08006886 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6887 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006888}
6889
Richard Smith6c3af3d2013-01-17 01:17:56 +00006890namespace {
6891/// \brief Visitor for expressions which looks for unsequenced operations on the
6892/// same object.
6893class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00006894 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6895
Richard Smith6c3af3d2013-01-17 01:17:56 +00006896 /// \brief A tree of sequenced regions within an expression. Two regions are
6897 /// unsequenced if one is an ancestor or a descendent of the other. When we
6898 /// finish processing an expression with sequencing, such as a comma
6899 /// expression, we fold its tree nodes into its parent, since they are
6900 /// unsequenced with respect to nodes we will visit later.
6901 class SequenceTree {
6902 struct Value {
6903 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6904 unsigned Parent : 31;
6905 bool Merged : 1;
6906 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00006907 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006908
6909 public:
6910 /// \brief A region within an expression which may be sequenced with respect
6911 /// to some other region.
6912 class Seq {
6913 explicit Seq(unsigned N) : Index(N) {}
6914 unsigned Index;
6915 friend class SequenceTree;
6916 public:
6917 Seq() : Index(0) {}
6918 };
6919
6920 SequenceTree() { Values.push_back(Value(0)); }
6921 Seq root() const { return Seq(0); }
6922
6923 /// \brief Create a new sequence of operations, which is an unsequenced
6924 /// subset of \p Parent. This sequence of operations is sequenced with
6925 /// respect to other children of \p Parent.
6926 Seq allocate(Seq Parent) {
6927 Values.push_back(Value(Parent.Index));
6928 return Seq(Values.size() - 1);
6929 }
6930
6931 /// \brief Merge a sequence of operations into its parent.
6932 void merge(Seq S) {
6933 Values[S.Index].Merged = true;
6934 }
6935
6936 /// \brief Determine whether two operations are unsequenced. This operation
6937 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6938 /// should have been merged into its parent as appropriate.
6939 bool isUnsequenced(Seq Cur, Seq Old) {
6940 unsigned C = representative(Cur.Index);
6941 unsigned Target = representative(Old.Index);
6942 while (C >= Target) {
6943 if (C == Target)
6944 return true;
6945 C = Values[C].Parent;
6946 }
6947 return false;
6948 }
6949
6950 private:
6951 /// \brief Pick a representative for a sequence.
6952 unsigned representative(unsigned K) {
6953 if (Values[K].Merged)
6954 // Perform path compression as we go.
6955 return Values[K].Parent = representative(Values[K].Parent);
6956 return K;
6957 }
6958 };
6959
6960 /// An object for which we can track unsequenced uses.
6961 typedef NamedDecl *Object;
6962
6963 /// Different flavors of object usage which we track. We only track the
6964 /// least-sequenced usage of each kind.
6965 enum UsageKind {
6966 /// A read of an object. Multiple unsequenced reads are OK.
6967 UK_Use,
6968 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00006969 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00006970 UK_ModAsValue,
6971 /// A modification of an object which is not sequenced before the value
6972 /// computation of the expression, such as n++.
6973 UK_ModAsSideEffect,
6974
6975 UK_Count = UK_ModAsSideEffect + 1
6976 };
6977
6978 struct Usage {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006979 Usage() : Use(nullptr), Seq() {}
Richard Smith6c3af3d2013-01-17 01:17:56 +00006980 Expr *Use;
6981 SequenceTree::Seq Seq;
6982 };
6983
6984 struct UsageInfo {
6985 UsageInfo() : Diagnosed(false) {}
6986 Usage Uses[UK_Count];
6987 /// Have we issued a diagnostic for this variable already?
6988 bool Diagnosed;
6989 };
6990 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6991
6992 Sema &SemaRef;
6993 /// Sequenced regions within the expression.
6994 SequenceTree Tree;
6995 /// Declaration modifications and references which we have seen.
6996 UsageInfoMap UsageMap;
6997 /// The region we are currently within.
6998 SequenceTree::Seq Region;
6999 /// Filled in with declarations which were modified as a side-effect
7000 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00007001 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007002 /// Expressions to check later. We defer checking these to reduce
7003 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007004 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007005
7006 /// RAII object wrapping the visitation of a sequenced subexpression of an
7007 /// expression. At the end of this process, the side-effects of the evaluation
7008 /// become sequenced with respect to the value computation of the result, so
7009 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7010 /// UK_ModAsValue.
7011 struct SequencedSubexpression {
7012 SequencedSubexpression(SequenceChecker &Self)
7013 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7014 Self.ModAsSideEffect = &ModAsSideEffect;
7015 }
7016 ~SequencedSubexpression() {
7017 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
7018 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
7019 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
7020 Self.addUsage(U, ModAsSideEffect[I].first,
7021 ModAsSideEffect[I].second.Use, UK_ModAsValue);
7022 }
7023 Self.ModAsSideEffect = OldModAsSideEffect;
7024 }
7025
7026 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00007027 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7028 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007029 };
7030
Richard Smith67470052013-06-20 22:21:56 +00007031 /// RAII object wrapping the visitation of a subexpression which we might
7032 /// choose to evaluate as a constant. If any subexpression is evaluated and
7033 /// found to be non-constant, this allows us to suppress the evaluation of
7034 /// the outer expression.
7035 class EvaluationTracker {
7036 public:
7037 EvaluationTracker(SequenceChecker &Self)
7038 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7039 Self.EvalTracker = this;
7040 }
7041 ~EvaluationTracker() {
7042 Self.EvalTracker = Prev;
7043 if (Prev)
7044 Prev->EvalOK &= EvalOK;
7045 }
7046
7047 bool evaluate(const Expr *E, bool &Result) {
7048 if (!EvalOK || E->isValueDependent())
7049 return false;
7050 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7051 return EvalOK;
7052 }
7053
7054 private:
7055 SequenceChecker &Self;
7056 EvaluationTracker *Prev;
7057 bool EvalOK;
7058 } *EvalTracker;
7059
Richard Smith6c3af3d2013-01-17 01:17:56 +00007060 /// \brief Find the object which is produced by the specified expression,
7061 /// if any.
7062 Object getObject(Expr *E, bool Mod) const {
7063 E = E->IgnoreParenCasts();
7064 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7065 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7066 return getObject(UO->getSubExpr(), Mod);
7067 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7068 if (BO->getOpcode() == BO_Comma)
7069 return getObject(BO->getRHS(), Mod);
7070 if (Mod && BO->isAssignmentOp())
7071 return getObject(BO->getLHS(), Mod);
7072 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7073 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7074 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7075 return ME->getMemberDecl();
7076 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7077 // FIXME: If this is a reference, map through to its value.
7078 return DRE->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007079 return nullptr;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007080 }
7081
7082 /// \brief Note that an object was modified or used by an expression.
7083 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7084 Usage &U = UI.Uses[UK];
7085 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7086 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7087 ModAsSideEffect->push_back(std::make_pair(O, U));
7088 U.Use = Ref;
7089 U.Seq = Region;
7090 }
7091 }
7092 /// \brief Check whether a modification or use conflicts with a prior usage.
7093 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7094 bool IsModMod) {
7095 if (UI.Diagnosed)
7096 return;
7097
7098 const Usage &U = UI.Uses[OtherKind];
7099 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7100 return;
7101
7102 Expr *Mod = U.Use;
7103 Expr *ModOrUse = Ref;
7104 if (OtherKind == UK_Use)
7105 std::swap(Mod, ModOrUse);
7106
7107 SemaRef.Diag(Mod->getExprLoc(),
7108 IsModMod ? diag::warn_unsequenced_mod_mod
7109 : diag::warn_unsequenced_mod_use)
7110 << O << SourceRange(ModOrUse->getExprLoc());
7111 UI.Diagnosed = true;
7112 }
7113
7114 void notePreUse(Object O, Expr *Use) {
7115 UsageInfo &U = UsageMap[O];
7116 // Uses conflict with other modifications.
7117 checkUsage(O, U, Use, UK_ModAsValue, false);
7118 }
7119 void notePostUse(Object O, Expr *Use) {
7120 UsageInfo &U = UsageMap[O];
7121 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7122 addUsage(U, O, Use, UK_Use);
7123 }
7124
7125 void notePreMod(Object O, Expr *Mod) {
7126 UsageInfo &U = UsageMap[O];
7127 // Modifications conflict with other modifications and with uses.
7128 checkUsage(O, U, Mod, UK_ModAsValue, true);
7129 checkUsage(O, U, Mod, UK_Use, false);
7130 }
7131 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7132 UsageInfo &U = UsageMap[O];
7133 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7134 addUsage(U, O, Use, UK);
7135 }
7136
7137public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00007138 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007139 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7140 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007141 Visit(E);
7142 }
7143
7144 void VisitStmt(Stmt *S) {
7145 // Skip all statements which aren't expressions for now.
7146 }
7147
7148 void VisitExpr(Expr *E) {
7149 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00007150 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007151 }
7152
7153 void VisitCastExpr(CastExpr *E) {
7154 Object O = Object();
7155 if (E->getCastKind() == CK_LValueToRValue)
7156 O = getObject(E->getSubExpr(), false);
7157
7158 if (O)
7159 notePreUse(O, E);
7160 VisitExpr(E);
7161 if (O)
7162 notePostUse(O, E);
7163 }
7164
7165 void VisitBinComma(BinaryOperator *BO) {
7166 // C++11 [expr.comma]p1:
7167 // Every value computation and side effect associated with the left
7168 // expression is sequenced before every value computation and side
7169 // effect associated with the right expression.
7170 SequenceTree::Seq LHS = Tree.allocate(Region);
7171 SequenceTree::Seq RHS = Tree.allocate(Region);
7172 SequenceTree::Seq OldRegion = Region;
7173
7174 {
7175 SequencedSubexpression SeqLHS(*this);
7176 Region = LHS;
7177 Visit(BO->getLHS());
7178 }
7179
7180 Region = RHS;
7181 Visit(BO->getRHS());
7182
7183 Region = OldRegion;
7184
7185 // Forget that LHS and RHS are sequenced. They are both unsequenced
7186 // with respect to other stuff.
7187 Tree.merge(LHS);
7188 Tree.merge(RHS);
7189 }
7190
7191 void VisitBinAssign(BinaryOperator *BO) {
7192 // The modification is sequenced after the value computation of the LHS
7193 // and RHS, so check it before inspecting the operands and update the
7194 // map afterwards.
7195 Object O = getObject(BO->getLHS(), true);
7196 if (!O)
7197 return VisitExpr(BO);
7198
7199 notePreMod(O, BO);
7200
7201 // C++11 [expr.ass]p7:
7202 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7203 // only once.
7204 //
7205 // Therefore, for a compound assignment operator, O is considered used
7206 // everywhere except within the evaluation of E1 itself.
7207 if (isa<CompoundAssignOperator>(BO))
7208 notePreUse(O, BO);
7209
7210 Visit(BO->getLHS());
7211
7212 if (isa<CompoundAssignOperator>(BO))
7213 notePostUse(O, BO);
7214
7215 Visit(BO->getRHS());
7216
Richard Smith418dd3e2013-06-26 23:16:51 +00007217 // C++11 [expr.ass]p1:
7218 // the assignment is sequenced [...] before the value computation of the
7219 // assignment expression.
7220 // C11 6.5.16/3 has no such rule.
7221 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7222 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007223 }
7224 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7225 VisitBinAssign(CAO);
7226 }
7227
7228 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7229 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7230 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7231 Object O = getObject(UO->getSubExpr(), true);
7232 if (!O)
7233 return VisitExpr(UO);
7234
7235 notePreMod(O, UO);
7236 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00007237 // C++11 [expr.pre.incr]p1:
7238 // the expression ++x is equivalent to x+=1
7239 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7240 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007241 }
7242
7243 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7244 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7245 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7246 Object O = getObject(UO->getSubExpr(), true);
7247 if (!O)
7248 return VisitExpr(UO);
7249
7250 notePreMod(O, UO);
7251 Visit(UO->getSubExpr());
7252 notePostMod(O, UO, UK_ModAsSideEffect);
7253 }
7254
7255 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7256 void VisitBinLOr(BinaryOperator *BO) {
7257 // The side-effects of the LHS of an '&&' are sequenced before the
7258 // value computation of the RHS, and hence before the value computation
7259 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7260 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00007261 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007262 {
7263 SequencedSubexpression Sequenced(*this);
7264 Visit(BO->getLHS());
7265 }
7266
7267 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007268 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007269 if (!Result)
7270 Visit(BO->getRHS());
7271 } else {
7272 // Check for unsequenced operations in the RHS, treating it as an
7273 // entirely separate evaluation.
7274 //
7275 // FIXME: If there are operations in the RHS which are unsequenced
7276 // with respect to operations outside the RHS, and those operations
7277 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00007278 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007279 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007280 }
7281 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00007282 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007283 {
7284 SequencedSubexpression Sequenced(*this);
7285 Visit(BO->getLHS());
7286 }
7287
7288 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007289 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007290 if (Result)
7291 Visit(BO->getRHS());
7292 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007293 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007294 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007295 }
7296
7297 // Only visit the condition, unless we can be sure which subexpression will
7298 // be chosen.
7299 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00007300 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00007301 {
7302 SequencedSubexpression Sequenced(*this);
7303 Visit(CO->getCond());
7304 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007305
7306 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007307 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00007308 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007309 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007310 WorkList.push_back(CO->getTrueExpr());
7311 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007312 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007313 }
7314
Richard Smith0c0b3902013-06-30 10:40:20 +00007315 void VisitCallExpr(CallExpr *CE) {
7316 // C++11 [intro.execution]p15:
7317 // When calling a function [...], every value computation and side effect
7318 // associated with any argument expression, or with the postfix expression
7319 // designating the called function, is sequenced before execution of every
7320 // expression or statement in the body of the function [and thus before
7321 // the value computation of its result].
7322 SequencedSubexpression Sequenced(*this);
7323 Base::VisitCallExpr(CE);
7324
7325 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7326 }
7327
Richard Smith6c3af3d2013-01-17 01:17:56 +00007328 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00007329 // This is a call, so all subexpressions are sequenced before the result.
7330 SequencedSubexpression Sequenced(*this);
7331
Richard Smith6c3af3d2013-01-17 01:17:56 +00007332 if (!CCE->isListInitialization())
7333 return VisitExpr(CCE);
7334
7335 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007336 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007337 SequenceTree::Seq Parent = Region;
7338 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7339 E = CCE->arg_end();
7340 I != E; ++I) {
7341 Region = Tree.allocate(Parent);
7342 Elts.push_back(Region);
7343 Visit(*I);
7344 }
7345
7346 // Forget that the initializers are sequenced.
7347 Region = Parent;
7348 for (unsigned I = 0; I < Elts.size(); ++I)
7349 Tree.merge(Elts[I]);
7350 }
7351
7352 void VisitInitListExpr(InitListExpr *ILE) {
7353 if (!SemaRef.getLangOpts().CPlusPlus11)
7354 return VisitExpr(ILE);
7355
7356 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007357 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007358 SequenceTree::Seq Parent = Region;
7359 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7360 Expr *E = ILE->getInit(I);
7361 if (!E) continue;
7362 Region = Tree.allocate(Parent);
7363 Elts.push_back(Region);
7364 Visit(E);
7365 }
7366
7367 // Forget that the initializers are sequenced.
7368 Region = Parent;
7369 for (unsigned I = 0; I < Elts.size(); ++I)
7370 Tree.merge(Elts[I]);
7371 }
7372};
7373}
7374
7375void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00007376 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007377 WorkList.push_back(E);
7378 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00007379 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00007380 SequenceChecker(*this, Item, WorkList);
7381 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007382}
7383
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007384void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7385 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007386 CheckImplicitConversions(E, CheckLoc);
7387 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007388 if (!IsConstexpr && !E->isValueDependent())
7389 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007390}
7391
John McCall15d7d122010-11-11 03:21:53 +00007392void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7393 FieldDecl *BitField,
7394 Expr *Init) {
7395 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7396}
7397
Mike Stumpf8c49212010-01-21 03:59:47 +00007398/// CheckParmsForFunctionDef - Check that the parameters of the given
7399/// function are appropriate for the definition of a function. This
7400/// takes care of any checks that cannot be performed on the
7401/// declaration itself, e.g., that the types of each of the function
7402/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00007403bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7404 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00007405 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007406 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00007407 for (; P != PEnd; ++P) {
7408 ParmVarDecl *Param = *P;
7409
Mike Stumpf8c49212010-01-21 03:59:47 +00007410 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7411 // function declarator that is part of a function definition of
7412 // that function shall not have incomplete type.
7413 //
7414 // This is also C++ [dcl.fct]p6.
7415 if (!Param->isInvalidDecl() &&
7416 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007417 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007418 Param->setInvalidDecl();
7419 HasInvalidParm = true;
7420 }
7421
7422 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7423 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00007424 if (CheckParameterNames &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007425 Param->getIdentifier() == nullptr &&
Mike Stumpf8c49212010-01-21 03:59:47 +00007426 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007427 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00007428 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00007429
7430 // C99 6.7.5.3p12:
7431 // If the function declarator is not part of a definition of that
7432 // function, parameters may have incomplete type and may use the [*]
7433 // notation in their sequences of declarator specifiers to specify
7434 // variable length array types.
7435 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007436 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00007437 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00007438 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00007439 // information is added for it.
7440 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007441 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00007442 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007443 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00007444 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007445
7446 // MSVC destroys objects passed by value in the callee. Therefore a
7447 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07007448 // object's destructor. However, we don't perform any direct access check
7449 // on the dtor.
7450 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7451 .getCXXABI()
7452 .areArgsDestroyedLeftToRightInCallee()) {
7453 if (!Param->isInvalidDecl()) {
7454 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7455 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7456 if (!ClassDecl->isInvalidDecl() &&
7457 !ClassDecl->hasIrrelevantDestructor() &&
7458 !ClassDecl->isDependentContext()) {
7459 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7460 MarkFunctionReferenced(Param->getLocation(), Destructor);
7461 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7462 }
7463 }
7464 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007465 }
Mike Stumpf8c49212010-01-21 03:59:47 +00007466 }
7467
7468 return HasInvalidParm;
7469}
John McCallb7f4ffe2010-08-12 21:44:57 +00007470
7471/// CheckCastAlign - Implements -Wcast-align, which warns when a
7472/// pointer cast increases the alignment requirements.
7473void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7474 // This is actually a lot of work to potentially be doing on every
7475 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007476 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCallb7f4ffe2010-08-12 21:44:57 +00007477 return;
7478
7479 // Ignore dependent types.
7480 if (T->isDependentType() || Op->getType()->isDependentType())
7481 return;
7482
7483 // Require that the destination be a pointer type.
7484 const PointerType *DestPtr = T->getAs<PointerType>();
7485 if (!DestPtr) return;
7486
7487 // If the destination has alignment 1, we're done.
7488 QualType DestPointee = DestPtr->getPointeeType();
7489 if (DestPointee->isIncompleteType()) return;
7490 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7491 if (DestAlign.isOne()) return;
7492
7493 // Require that the source be a pointer type.
7494 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7495 if (!SrcPtr) return;
7496 QualType SrcPointee = SrcPtr->getPointeeType();
7497
7498 // Whitelist casts from cv void*. We already implicitly
7499 // whitelisted casts to cv void*, since they have alignment 1.
7500 // Also whitelist casts involving incomplete types, which implicitly
7501 // includes 'void'.
7502 if (SrcPointee->isIncompleteType()) return;
7503
7504 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7505 if (SrcAlign >= DestAlign) return;
7506
7507 Diag(TRange.getBegin(), diag::warn_cast_align)
7508 << Op->getType() << T
7509 << static_cast<unsigned>(SrcAlign.getQuantity())
7510 << static_cast<unsigned>(DestAlign.getQuantity())
7511 << TRange << Op->getSourceRange();
7512}
7513
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007514static const Type* getElementType(const Expr *BaseExpr) {
7515 const Type* EltType = BaseExpr->getType().getTypePtr();
7516 if (EltType->isAnyPointerType())
7517 return EltType->getPointeeType().getTypePtr();
7518 else if (EltType->isArrayType())
7519 return EltType->getBaseElementTypeUnsafe();
7520 return EltType;
7521}
7522
Chandler Carruthc2684342011-08-05 09:10:50 +00007523/// \brief Check whether this array fits the idiom of a size-one tail padded
7524/// array member of a struct.
7525///
7526/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7527/// commonly used to emulate flexible arrays in C89 code.
7528static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7529 const NamedDecl *ND) {
7530 if (Size != 1 || !ND) return false;
7531
7532 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7533 if (!FD) return false;
7534
7535 // Don't consider sizes resulting from macro expansions or template argument
7536 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00007537
7538 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007539 while (TInfo) {
7540 TypeLoc TL = TInfo->getTypeLoc();
7541 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00007542 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7543 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007544 TInfo = TDL->getTypeSourceInfo();
7545 continue;
7546 }
David Blaikie39e6ab42013-02-18 22:06:02 +00007547 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7548 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00007549 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7550 return false;
7551 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007552 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00007553 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007554
7555 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00007556 if (!RD) return false;
7557 if (RD->isUnion()) return false;
7558 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7559 if (!CRD->isStandardLayout()) return false;
7560 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007561
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00007562 // See if this is the last field decl in the record.
7563 const Decl *D = FD;
7564 while ((D = D->getNextDeclInContext()))
7565 if (isa<FieldDecl>(D))
7566 return false;
7567 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00007568}
7569
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007570void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007571 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00007572 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00007573 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007574 if (IndexExpr->isValueDependent())
7575 return;
7576
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00007577 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007578 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00007579 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007580 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00007581 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00007582 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00007583
Chandler Carruth34064582011-02-17 20:55:08 +00007584 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007585 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00007586 return;
Richard Smith25b009a2011-12-16 19:31:14 +00007587 if (IndexNegated)
7588 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007589
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007590 const NamedDecl *ND = nullptr;
Chandler Carruthba447122011-08-05 08:07:29 +00007591 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7592 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00007593 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00007594 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00007595
Ted Kremenek9e060ca2011-02-23 23:06:04 +00007596 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00007597 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00007598 if (!size.isStrictlyPositive())
7599 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007600
7601 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00007602 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007603 // Make sure we're comparing apples to apples when comparing index to size
7604 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7605 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00007606 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00007607 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007608 if (ptrarith_typesize != array_typesize) {
7609 // There's a cast to a different size type involved
7610 uint64_t ratio = array_typesize / ptrarith_typesize;
7611 // TODO: Be smarter about handling cases where array_typesize is not a
7612 // multiple of ptrarith_typesize
7613 if (ptrarith_typesize * ratio == array_typesize)
7614 size *= llvm::APInt(size.getBitWidth(), ratio);
7615 }
7616 }
7617
Chandler Carruth34064582011-02-17 20:55:08 +00007618 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007619 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007620 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007621 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007622
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007623 // For array subscripting the index must be less than size, but for pointer
7624 // arithmetic also allow the index (offset) to be equal to size since
7625 // computing the next address after the end of the array is legal and
7626 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00007627 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00007628 return;
7629
7630 // Also don't warn for arrays of size 1 which are members of some
7631 // structure. These are often used to approximate flexible arrays in C89
7632 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007633 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007634 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007635
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007636 // Suppress the warning if the subscript expression (as identified by the
7637 // ']' location) and the index expression are both from macro expansions
7638 // within a system header.
7639 if (ASE) {
7640 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7641 ASE->getRBracketLoc());
7642 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7643 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7644 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00007645 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007646 return;
7647 }
7648 }
7649
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007650 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007651 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007652 DiagID = diag::warn_array_index_exceeds_bounds;
7653
7654 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7655 PDiag(DiagID) << index.toString(10, true)
7656 << size.toString(10, true)
7657 << (unsigned)size.getLimitedValue(~0U)
7658 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00007659 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007660 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007661 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007662 DiagID = diag::warn_ptr_arith_precedes_bounds;
7663 if (index.isNegative()) index = -index;
7664 }
7665
7666 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7667 PDiag(DiagID) << index.toString(10, true)
7668 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007669 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00007670
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00007671 if (!ND) {
7672 // Try harder to find a NamedDecl to point at in the note.
7673 while (const ArraySubscriptExpr *ASE =
7674 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7675 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7677 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7678 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7679 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7680 }
7681
Chandler Carruth35001ca2011-02-17 21:10:52 +00007682 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007683 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7684 PDiag(diag::note_array_index_out_of_bounds)
7685 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007686}
7687
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007688void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007689 int AllowOnePastEnd = 0;
7690 while (expr) {
7691 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007692 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007693 case Stmt::ArraySubscriptExprClass: {
7694 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007695 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007696 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007697 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007698 }
7699 case Stmt::UnaryOperatorClass: {
7700 // Only unwrap the * and & unary operators
7701 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7702 expr = UO->getSubExpr();
7703 switch (UO->getOpcode()) {
7704 case UO_AddrOf:
7705 AllowOnePastEnd++;
7706 break;
7707 case UO_Deref:
7708 AllowOnePastEnd--;
7709 break;
7710 default:
7711 return;
7712 }
7713 break;
7714 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007715 case Stmt::ConditionalOperatorClass: {
7716 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7717 if (const Expr *lhs = cond->getLHS())
7718 CheckArrayAccess(lhs);
7719 if (const Expr *rhs = cond->getRHS())
7720 CheckArrayAccess(rhs);
7721 return;
7722 }
7723 default:
7724 return;
7725 }
Peter Collingbournef111d932011-04-15 00:35:48 +00007726 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007727}
John McCallf85e1932011-06-15 23:02:42 +00007728
7729//===--- CHECK: Objective-C retain cycles ----------------------------------//
7730
7731namespace {
7732 struct RetainCycleOwner {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007733 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCallf85e1932011-06-15 23:02:42 +00007734 VarDecl *Variable;
7735 SourceRange Range;
7736 SourceLocation Loc;
7737 bool Indirect;
7738
7739 void setLocsFrom(Expr *e) {
7740 Loc = e->getExprLoc();
7741 Range = e->getSourceRange();
7742 }
7743 };
7744}
7745
7746/// Consider whether capturing the given variable can possibly lead to
7747/// a retain cycle.
7748static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00007749 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00007750 // lifetime. In MRR, it's captured strongly if the variable is
7751 // __block and has an appropriate type.
7752 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7753 return false;
7754
7755 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00007756 if (ref)
7757 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00007758 return true;
7759}
7760
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007761static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00007762 while (true) {
7763 e = e->IgnoreParens();
7764 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7765 switch (cast->getCastKind()) {
7766 case CK_BitCast:
7767 case CK_LValueBitCast:
7768 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00007769 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00007770 e = cast->getSubExpr();
7771 continue;
7772
John McCallf85e1932011-06-15 23:02:42 +00007773 default:
7774 return false;
7775 }
7776 }
7777
7778 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7779 ObjCIvarDecl *ivar = ref->getDecl();
7780 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7781 return false;
7782
7783 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007784 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007785 return false;
7786
7787 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7788 owner.Indirect = true;
7789 return true;
7790 }
7791
7792 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7793 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7794 if (!var) return false;
7795 return considerVariable(var, ref, owner);
7796 }
7797
John McCallf85e1932011-06-15 23:02:42 +00007798 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7799 if (member->isArrow()) return false;
7800
7801 // Don't count this as an indirect ownership.
7802 e = member->getBase();
7803 continue;
7804 }
7805
John McCall4b9c2d22011-11-06 09:01:30 +00007806 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7807 // Only pay attention to pseudo-objects on property references.
7808 ObjCPropertyRefExpr *pre
7809 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7810 ->IgnoreParens());
7811 if (!pre) return false;
7812 if (pre->isImplicitProperty()) return false;
7813 ObjCPropertyDecl *property = pre->getExplicitProperty();
7814 if (!property->isRetaining() &&
7815 !(property->getPropertyIvarDecl() &&
7816 property->getPropertyIvarDecl()->getType()
7817 .getObjCLifetime() == Qualifiers::OCL_Strong))
7818 return false;
7819
7820 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007821 if (pre->isSuperReceiver()) {
7822 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7823 if (!owner.Variable)
7824 return false;
7825 owner.Loc = pre->getLocation();
7826 owner.Range = pre->getSourceRange();
7827 return true;
7828 }
John McCall4b9c2d22011-11-06 09:01:30 +00007829 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7830 ->getSourceExpr());
7831 continue;
7832 }
7833
John McCallf85e1932011-06-15 23:02:42 +00007834 // Array ivars?
7835
7836 return false;
7837 }
7838}
7839
7840namespace {
7841 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7842 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7843 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007844 Context(Context), Variable(variable), Capturer(nullptr),
7845 VarWillBeReased(false) {}
7846 ASTContext &Context;
John McCallf85e1932011-06-15 23:02:42 +00007847 VarDecl *Variable;
7848 Expr *Capturer;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007849 bool VarWillBeReased;
John McCallf85e1932011-06-15 23:02:42 +00007850
7851 void VisitDeclRefExpr(DeclRefExpr *ref) {
7852 if (ref->getDecl() == Variable && !Capturer)
7853 Capturer = ref;
7854 }
7855
John McCallf85e1932011-06-15 23:02:42 +00007856 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7857 if (Capturer) return;
7858 Visit(ref->getBase());
7859 if (Capturer && ref->isFreeIvar())
7860 Capturer = ref;
7861 }
7862
7863 void VisitBlockExpr(BlockExpr *block) {
7864 // Look inside nested blocks
7865 if (block->getBlockDecl()->capturesVariable(Variable))
7866 Visit(block->getBlockDecl()->getBody());
7867 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00007868
7869 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7870 if (Capturer) return;
7871 if (OVE->getSourceExpr())
7872 Visit(OVE->getSourceExpr());
7873 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007874 void VisitBinaryOperator(BinaryOperator *BinOp) {
7875 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7876 return;
7877 Expr *LHS = BinOp->getLHS();
7878 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7879 if (DRE->getDecl() != Variable)
7880 return;
7881 if (Expr *RHS = BinOp->getRHS()) {
7882 RHS = RHS->IgnoreParenCasts();
7883 llvm::APSInt Value;
7884 VarWillBeReased =
7885 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7886 }
7887 }
7888 }
John McCallf85e1932011-06-15 23:02:42 +00007889 };
7890}
7891
7892/// Check whether the given argument is a block which captures a
7893/// variable.
7894static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7895 assert(owner.Variable && owner.Loc.isValid());
7896
7897 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00007898
7899 // Look through [^{...} copy] and Block_copy(^{...}).
7900 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7901 Selector Cmd = ME->getSelector();
7902 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7903 e = ME->getInstanceReceiver();
7904 if (!e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007905 return nullptr;
Jordan Rose1fac58a2012-09-17 17:54:30 +00007906 e = e->IgnoreParenCasts();
7907 }
7908 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7909 if (CE->getNumArgs() == 1) {
7910 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00007911 if (Fn) {
7912 const IdentifierInfo *FnI = Fn->getIdentifier();
7913 if (FnI && FnI->isStr("_Block_copy")) {
7914 e = CE->getArg(0)->IgnoreParenCasts();
7915 }
7916 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00007917 }
7918 }
7919
John McCallf85e1932011-06-15 23:02:42 +00007920 BlockExpr *block = dyn_cast<BlockExpr>(e);
7921 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007922 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00007923
7924 FindCaptureVisitor visitor(S.Context, owner.Variable);
7925 visitor.Visit(block->getBlockDecl()->getBody());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007926 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCallf85e1932011-06-15 23:02:42 +00007927}
7928
7929static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7930 RetainCycleOwner &owner) {
7931 assert(capturer);
7932 assert(owner.Variable && owner.Loc.isValid());
7933
7934 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7935 << owner.Variable << capturer->getSourceRange();
7936 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7937 << owner.Indirect << owner.Range;
7938}
7939
7940/// Check for a keyword selector that starts with the word 'add' or
7941/// 'set'.
7942static bool isSetterLikeSelector(Selector sel) {
7943 if (sel.isUnarySelector()) return false;
7944
Chris Lattner5f9e2722011-07-23 10:55:15 +00007945 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00007946 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007947 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00007948 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007949 else if (str.startswith("add")) {
7950 // Specially whitelist 'addOperationWithBlock:'.
7951 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7952 return false;
7953 str = str.substr(3);
7954 }
John McCallf85e1932011-06-15 23:02:42 +00007955 else
7956 return false;
7957
7958 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00007959 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00007960}
7961
7962/// Check a message send to see if it's likely to cause a retain cycle.
7963void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7964 // Only check instance methods whose selector looks like a setter.
7965 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7966 return;
7967
7968 // Try to find a variable that the receiver is strongly owned by.
7969 RetainCycleOwner owner;
7970 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007971 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007972 return;
7973 } else {
7974 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7975 owner.Variable = getCurMethodDecl()->getSelfDecl();
7976 owner.Loc = msg->getSuperLoc();
7977 owner.Range = msg->getSuperLoc();
7978 }
7979
7980 // Check whether the receiver is captured by any of the arguments.
7981 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7982 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7983 return diagnoseRetainCycle(*this, capturer, owner);
7984}
7985
7986/// Check a property assign to see if it's likely to cause a retain cycle.
7987void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7988 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007989 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00007990 return;
7991
7992 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7993 diagnoseRetainCycle(*this, capturer, owner);
7994}
7995
Jordan Rosee10f4d32012-09-15 02:48:31 +00007996void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7997 RetainCycleOwner Owner;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007998 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosee10f4d32012-09-15 02:48:31 +00007999 return;
8000
8001 // Because we don't have an expression for the variable, we have to set the
8002 // location explicitly here.
8003 Owner.Loc = Var->getLocation();
8004 Owner.Range = Var->getSourceRange();
8005
8006 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8007 diagnoseRetainCycle(*this, Capturer, Owner);
8008}
8009
Ted Kremenek9d084012012-12-21 08:04:28 +00008010static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8011 Expr *RHS, bool isProperty) {
8012 // Check if RHS is an Objective-C object literal, which also can get
8013 // immediately zapped in a weak reference. Note that we explicitly
8014 // allow ObjCStringLiterals, since those are designed to never really die.
8015 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008016
Ted Kremenekd3292c82012-12-21 22:46:35 +00008017 // This enum needs to match with the 'select' in
8018 // warn_objc_arc_literal_assign (off-by-1).
8019 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8020 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8021 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00008022
8023 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00008024 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00008025 << (isProperty ? 0 : 1)
8026 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008027
8028 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00008029}
8030
Ted Kremenekb29b30f2012-12-21 19:45:30 +00008031static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8032 Qualifiers::ObjCLifetime LT,
8033 Expr *RHS, bool isProperty) {
8034 // Strip off any implicit cast added to get to the one ARC-specific.
8035 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8036 if (cast->getCastKind() == CK_ARCConsumeObject) {
8037 S.Diag(Loc, diag::warn_arc_retained_assign)
8038 << (LT == Qualifiers::OCL_ExplicitNone)
8039 << (isProperty ? 0 : 1)
8040 << RHS->getSourceRange();
8041 return true;
8042 }
8043 RHS = cast->getSubExpr();
8044 }
8045
8046 if (LT == Qualifiers::OCL_Weak &&
8047 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8048 return true;
8049
8050 return false;
8051}
8052
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008053bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8054 QualType LHS, Expr *RHS) {
8055 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8056
8057 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8058 return false;
8059
8060 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8061 return true;
8062
8063 return false;
8064}
8065
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008066void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8067 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008068 QualType LHSType;
8069 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07008070 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008071 ObjCPropertyRefExpr *PRE
8072 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8073 if (PRE && !PRE->isImplicitProperty()) {
8074 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8075 if (PD)
8076 LHSType = PD->getType();
8077 }
8078
8079 if (LHSType.isNull())
8080 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00008081
8082 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8083
8084 if (LT == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008085 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose7a270482012-09-28 22:21:35 +00008086 getCurFunction()->markSafeWeakUse(LHS);
8087 }
8088
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008089 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8090 return;
Jordan Rose7a270482012-09-28 22:21:35 +00008091
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008092 // FIXME. Check for other life times.
8093 if (LT != Qualifiers::OCL_None)
8094 return;
8095
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008096 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008097 if (PRE->isImplicitProperty())
8098 return;
8099 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8100 if (!PD)
8101 return;
8102
Bill Wendlingad017fa2012-12-20 19:22:21 +00008103 unsigned Attributes = PD->getPropertyAttributes();
8104 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008105 // when 'assign' attribute was not explicitly specified
8106 // by user, ignore it and rely on property type itself
8107 // for lifetime info.
8108 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8109 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8110 LHSType->isObjCRetainableType())
8111 return;
8112
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008113 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00008114 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008115 Diag(Loc, diag::warn_arc_retained_property_assign)
8116 << RHS->getSourceRange();
8117 return;
8118 }
8119 RHS = cast->getSubExpr();
8120 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008121 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00008122 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008123 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8124 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00008125 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008126 }
8127}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008128
8129//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8130
8131namespace {
8132bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8133 SourceLocation StmtLoc,
8134 const NullStmt *Body) {
8135 // Do not warn if the body is a macro that expands to nothing, e.g:
8136 //
8137 // #define CALL(x)
8138 // if (condition)
8139 // CALL(0);
8140 //
8141 if (Body->hasLeadingEmptyMacro())
8142 return false;
8143
8144 // Get line numbers of statement and body.
8145 bool StmtLineInvalid;
8146 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8147 &StmtLineInvalid);
8148 if (StmtLineInvalid)
8149 return false;
8150
8151 bool BodyLineInvalid;
8152 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8153 &BodyLineInvalid);
8154 if (BodyLineInvalid)
8155 return false;
8156
8157 // Warn if null statement and body are on the same line.
8158 if (StmtLine != BodyLine)
8159 return false;
8160
8161 return true;
8162}
8163} // Unnamed namespace
8164
8165void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8166 const Stmt *Body,
8167 unsigned DiagID) {
8168 // Since this is a syntactic check, don't emit diagnostic for template
8169 // instantiations, this just adds noise.
8170 if (CurrentInstantiationScope)
8171 return;
8172
8173 // The body should be a null statement.
8174 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8175 if (!NBody)
8176 return;
8177
8178 // Do the usual checks.
8179 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8180 return;
8181
8182 Diag(NBody->getSemiLoc(), DiagID);
8183 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8184}
8185
8186void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8187 const Stmt *PossibleBody) {
8188 assert(!CurrentInstantiationScope); // Ensured by caller
8189
8190 SourceLocation StmtLoc;
8191 const Stmt *Body;
8192 unsigned DiagID;
8193 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8194 StmtLoc = FS->getRParenLoc();
8195 Body = FS->getBody();
8196 DiagID = diag::warn_empty_for_body;
8197 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8198 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8199 Body = WS->getBody();
8200 DiagID = diag::warn_empty_while_body;
8201 } else
8202 return; // Neither `for' nor `while'.
8203
8204 // The body should be a null statement.
8205 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8206 if (!NBody)
8207 return;
8208
8209 // Skip expensive checks if diagnostic is disabled.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008210 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008211 return;
8212
8213 // Do the usual checks.
8214 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8215 return;
8216
8217 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8218 // noise level low, emit diagnostics only if for/while is followed by a
8219 // CompoundStmt, e.g.:
8220 // for (int i = 0; i < n; i++);
8221 // {
8222 // a(i);
8223 // }
8224 // or if for/while is followed by a statement with more indentation
8225 // than for/while itself:
8226 // for (int i = 0; i < n; i++);
8227 // a(i);
8228 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8229 if (!ProbableTypo) {
8230 bool BodyColInvalid;
8231 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8232 PossibleBody->getLocStart(),
8233 &BodyColInvalid);
8234 if (BodyColInvalid)
8235 return;
8236
8237 bool StmtColInvalid;
8238 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8239 S->getLocStart(),
8240 &StmtColInvalid);
8241 if (StmtColInvalid)
8242 return;
8243
8244 if (BodyCol > StmtCol)
8245 ProbableTypo = true;
8246 }
8247
8248 if (ProbableTypo) {
8249 Diag(NBody->getSemiLoc(), DiagID);
8250 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8251 }
8252}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008253
8254//===--- Layout compatibility ----------------------------------------------//
8255
8256namespace {
8257
8258bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8259
8260/// \brief Check if two enumeration types are layout-compatible.
8261bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8262 // C++11 [dcl.enum] p8:
8263 // Two enumeration types are layout-compatible if they have the same
8264 // underlying type.
8265 return ED1->isComplete() && ED2->isComplete() &&
8266 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8267}
8268
8269/// \brief Check if two fields are layout-compatible.
8270bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8271 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8272 return false;
8273
8274 if (Field1->isBitField() != Field2->isBitField())
8275 return false;
8276
8277 if (Field1->isBitField()) {
8278 // Make sure that the bit-fields are the same length.
8279 unsigned Bits1 = Field1->getBitWidthValue(C);
8280 unsigned Bits2 = Field2->getBitWidthValue(C);
8281
8282 if (Bits1 != Bits2)
8283 return false;
8284 }
8285
8286 return true;
8287}
8288
8289/// \brief Check if two standard-layout structs are layout-compatible.
8290/// (C++11 [class.mem] p17)
8291bool isLayoutCompatibleStruct(ASTContext &C,
8292 RecordDecl *RD1,
8293 RecordDecl *RD2) {
8294 // If both records are C++ classes, check that base classes match.
8295 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8296 // If one of records is a CXXRecordDecl we are in C++ mode,
8297 // thus the other one is a CXXRecordDecl, too.
8298 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8299 // Check number of base classes.
8300 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8301 return false;
8302
8303 // Check the base classes.
8304 for (CXXRecordDecl::base_class_const_iterator
8305 Base1 = D1CXX->bases_begin(),
8306 BaseEnd1 = D1CXX->bases_end(),
8307 Base2 = D2CXX->bases_begin();
8308 Base1 != BaseEnd1;
8309 ++Base1, ++Base2) {
8310 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8311 return false;
8312 }
8313 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8314 // If only RD2 is a C++ class, it should have zero base classes.
8315 if (D2CXX->getNumBases() > 0)
8316 return false;
8317 }
8318
8319 // Check the fields.
8320 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8321 Field2End = RD2->field_end(),
8322 Field1 = RD1->field_begin(),
8323 Field1End = RD1->field_end();
8324 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8325 if (!isLayoutCompatible(C, *Field1, *Field2))
8326 return false;
8327 }
8328 if (Field1 != Field1End || Field2 != Field2End)
8329 return false;
8330
8331 return true;
8332}
8333
8334/// \brief Check if two standard-layout unions are layout-compatible.
8335/// (C++11 [class.mem] p18)
8336bool isLayoutCompatibleUnion(ASTContext &C,
8337 RecordDecl *RD1,
8338 RecordDecl *RD2) {
8339 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07008340 for (auto *Field2 : RD2->fields())
8341 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008342
Stephen Hines651f13c2014-04-23 16:59:28 -07008343 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008344 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8345 I = UnmatchedFields.begin(),
8346 E = UnmatchedFields.end();
8347
8348 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008349 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008350 bool Result = UnmatchedFields.erase(*I);
8351 (void) Result;
8352 assert(Result);
8353 break;
8354 }
8355 }
8356 if (I == E)
8357 return false;
8358 }
8359
8360 return UnmatchedFields.empty();
8361}
8362
8363bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8364 if (RD1->isUnion() != RD2->isUnion())
8365 return false;
8366
8367 if (RD1->isUnion())
8368 return isLayoutCompatibleUnion(C, RD1, RD2);
8369 else
8370 return isLayoutCompatibleStruct(C, RD1, RD2);
8371}
8372
8373/// \brief Check if two types are layout-compatible in C++11 sense.
8374bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8375 if (T1.isNull() || T2.isNull())
8376 return false;
8377
8378 // C++11 [basic.types] p11:
8379 // If two types T1 and T2 are the same type, then T1 and T2 are
8380 // layout-compatible types.
8381 if (C.hasSameType(T1, T2))
8382 return true;
8383
8384 T1 = T1.getCanonicalType().getUnqualifiedType();
8385 T2 = T2.getCanonicalType().getUnqualifiedType();
8386
8387 const Type::TypeClass TC1 = T1->getTypeClass();
8388 const Type::TypeClass TC2 = T2->getTypeClass();
8389
8390 if (TC1 != TC2)
8391 return false;
8392
8393 if (TC1 == Type::Enum) {
8394 return isLayoutCompatible(C,
8395 cast<EnumType>(T1)->getDecl(),
8396 cast<EnumType>(T2)->getDecl());
8397 } else if (TC1 == Type::Record) {
8398 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8399 return false;
8400
8401 return isLayoutCompatible(C,
8402 cast<RecordType>(T1)->getDecl(),
8403 cast<RecordType>(T2)->getDecl());
8404 }
8405
8406 return false;
8407}
8408}
8409
8410//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8411
8412namespace {
8413/// \brief Given a type tag expression find the type tag itself.
8414///
8415/// \param TypeExpr Type tag expression, as it appears in user's code.
8416///
8417/// \param VD Declaration of an identifier that appears in a type tag.
8418///
8419/// \param MagicValue Type tag magic value.
8420bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8421 const ValueDecl **VD, uint64_t *MagicValue) {
8422 while(true) {
8423 if (!TypeExpr)
8424 return false;
8425
8426 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8427
8428 switch (TypeExpr->getStmtClass()) {
8429 case Stmt::UnaryOperatorClass: {
8430 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8431 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8432 TypeExpr = UO->getSubExpr();
8433 continue;
8434 }
8435 return false;
8436 }
8437
8438 case Stmt::DeclRefExprClass: {
8439 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8440 *VD = DRE->getDecl();
8441 return true;
8442 }
8443
8444 case Stmt::IntegerLiteralClass: {
8445 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8446 llvm::APInt MagicValueAPInt = IL->getValue();
8447 if (MagicValueAPInt.getActiveBits() <= 64) {
8448 *MagicValue = MagicValueAPInt.getZExtValue();
8449 return true;
8450 } else
8451 return false;
8452 }
8453
8454 case Stmt::BinaryConditionalOperatorClass:
8455 case Stmt::ConditionalOperatorClass: {
8456 const AbstractConditionalOperator *ACO =
8457 cast<AbstractConditionalOperator>(TypeExpr);
8458 bool Result;
8459 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8460 if (Result)
8461 TypeExpr = ACO->getTrueExpr();
8462 else
8463 TypeExpr = ACO->getFalseExpr();
8464 continue;
8465 }
8466 return false;
8467 }
8468
8469 case Stmt::BinaryOperatorClass: {
8470 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8471 if (BO->getOpcode() == BO_Comma) {
8472 TypeExpr = BO->getRHS();
8473 continue;
8474 }
8475 return false;
8476 }
8477
8478 default:
8479 return false;
8480 }
8481 }
8482}
8483
8484/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8485///
8486/// \param TypeExpr Expression that specifies a type tag.
8487///
8488/// \param MagicValues Registered magic values.
8489///
8490/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8491/// kind.
8492///
8493/// \param TypeInfo Information about the corresponding C type.
8494///
8495/// \returns true if the corresponding C type was found.
8496bool GetMatchingCType(
8497 const IdentifierInfo *ArgumentKind,
8498 const Expr *TypeExpr, const ASTContext &Ctx,
8499 const llvm::DenseMap<Sema::TypeTagMagicValue,
8500 Sema::TypeTagData> *MagicValues,
8501 bool &FoundWrongKind,
8502 Sema::TypeTagData &TypeInfo) {
8503 FoundWrongKind = false;
8504
8505 // Variable declaration that has type_tag_for_datatype attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008506 const ValueDecl *VD = nullptr;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008507
8508 uint64_t MagicValue;
8509
8510 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8511 return false;
8512
8513 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008514 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008515 if (I->getArgumentKind() != ArgumentKind) {
8516 FoundWrongKind = true;
8517 return false;
8518 }
8519 TypeInfo.Type = I->getMatchingCType();
8520 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8521 TypeInfo.MustBeNull = I->getMustBeNull();
8522 return true;
8523 }
8524 return false;
8525 }
8526
8527 if (!MagicValues)
8528 return false;
8529
8530 llvm::DenseMap<Sema::TypeTagMagicValue,
8531 Sema::TypeTagData>::const_iterator I =
8532 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8533 if (I == MagicValues->end())
8534 return false;
8535
8536 TypeInfo = I->second;
8537 return true;
8538}
8539} // unnamed namespace
8540
8541void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8542 uint64_t MagicValue, QualType Type,
8543 bool LayoutCompatible,
8544 bool MustBeNull) {
8545 if (!TypeTagForDatatypeMagicValues)
8546 TypeTagForDatatypeMagicValues.reset(
8547 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8548
8549 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8550 (*TypeTagForDatatypeMagicValues)[Magic] =
8551 TypeTagData(Type, LayoutCompatible, MustBeNull);
8552}
8553
8554namespace {
8555bool IsSameCharType(QualType T1, QualType T2) {
8556 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8557 if (!BT1)
8558 return false;
8559
8560 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8561 if (!BT2)
8562 return false;
8563
8564 BuiltinType::Kind T1Kind = BT1->getKind();
8565 BuiltinType::Kind T2Kind = BT2->getKind();
8566
8567 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8568 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8569 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8570 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8571}
8572} // unnamed namespace
8573
8574void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8575 const Expr * const *ExprArgs) {
8576 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8577 bool IsPointerAttr = Attr->getIsPointer();
8578
8579 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8580 bool FoundWrongKind;
8581 TypeTagData TypeInfo;
8582 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8583 TypeTagForDatatypeMagicValues.get(),
8584 FoundWrongKind, TypeInfo)) {
8585 if (FoundWrongKind)
8586 Diag(TypeTagExpr->getExprLoc(),
8587 diag::warn_type_tag_for_datatype_wrong_kind)
8588 << TypeTagExpr->getSourceRange();
8589 return;
8590 }
8591
8592 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8593 if (IsPointerAttr) {
8594 // Skip implicit cast of pointer to `void *' (as a function argument).
8595 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00008596 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00008597 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008598 ArgumentExpr = ICE->getSubExpr();
8599 }
8600 QualType ArgumentType = ArgumentExpr->getType();
8601
8602 // Passing a `void*' pointer shouldn't trigger a warning.
8603 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8604 return;
8605
8606 if (TypeInfo.MustBeNull) {
8607 // Type tag with matching void type requires a null pointer.
8608 if (!ArgumentExpr->isNullPointerConstant(Context,
8609 Expr::NPC_ValueDependentIsNotNull)) {
8610 Diag(ArgumentExpr->getExprLoc(),
8611 diag::warn_type_safety_null_pointer_required)
8612 << ArgumentKind->getName()
8613 << ArgumentExpr->getSourceRange()
8614 << TypeTagExpr->getSourceRange();
8615 }
8616 return;
8617 }
8618
8619 QualType RequiredType = TypeInfo.Type;
8620 if (IsPointerAttr)
8621 RequiredType = Context.getPointerType(RequiredType);
8622
8623 bool mismatch = false;
8624 if (!TypeInfo.LayoutCompatible) {
8625 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8626
8627 // C++11 [basic.fundamental] p1:
8628 // Plain char, signed char, and unsigned char are three distinct types.
8629 //
8630 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8631 // char' depending on the current char signedness mode.
8632 if (mismatch)
8633 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8634 RequiredType->getPointeeType())) ||
8635 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8636 mismatch = false;
8637 } else
8638 if (IsPointerAttr)
8639 mismatch = !isLayoutCompatible(Context,
8640 ArgumentType->getPointeeType(),
8641 RequiredType->getPointeeType());
8642 else
8643 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8644
8645 if (mismatch)
8646 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07008647 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008648 << TypeInfo.LayoutCompatible << RequiredType
8649 << ArgumentExpr->getSourceRange()
8650 << TypeTagExpr->getSourceRange();
8651}
Stephen Hines651f13c2014-04-23 16:59:28 -07008652