blob: 953b3f67d2f86ecee05c8e8489febf47ef60e883 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-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 Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000116 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000148 case Builtin::BI__va_start: {
149 switch (Context.getTargetInfo().getTriple().getArch()) {
150 case llvm::Triple::arm:
151 case llvm::Triple::thumb:
152 if (SemaBuiltinVAStartARM(TheCall))
153 return ExprError();
154 break;
155 default:
156 if (SemaBuiltinVAStart(TheCall))
157 return ExprError();
158 break;
159 }
160 break;
161 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000162 case Builtin::BI__builtin_isgreater:
163 case Builtin::BI__builtin_isgreaterequal:
164 case Builtin::BI__builtin_isless:
165 case Builtin::BI__builtin_islessequal:
166 case Builtin::BI__builtin_islessgreater:
167 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000168 if (SemaBuiltinUnorderedCompare(TheCall))
169 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000170 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000171 case Builtin::BI__builtin_fpclassify:
172 if (SemaBuiltinFPClassification(TheCall, 6))
173 return ExprError();
174 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000175 case Builtin::BI__builtin_isfinite:
176 case Builtin::BI__builtin_isinf:
177 case Builtin::BI__builtin_isinf_sign:
178 case Builtin::BI__builtin_isnan:
179 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000180 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000181 return ExprError();
182 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000183 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000184 return SemaBuiltinShuffleVector(TheCall);
185 // TheCall will be freed by the smart pointer here, but that's fine, since
186 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000187 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000188 if (SemaBuiltinPrefetch(TheCall))
189 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000190 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000191 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000192 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000193 if (SemaBuiltinAssume(TheCall))
194 return ExprError();
195 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000196 case Builtin::BI__builtin_assume_aligned:
197 if (SemaBuiltinAssumeAligned(TheCall))
198 return ExprError();
199 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000200 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000201 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000202 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000203 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000204 case Builtin::BI__builtin_longjmp:
205 if (SemaBuiltinLongjmp(TheCall))
206 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000207 break;
John McCallbebede42011-02-26 05:39:39 +0000208
209 case Builtin::BI__builtin_classify_type:
210 if (checkArgCount(*this, TheCall, 1)) return true;
211 TheCall->setType(Context.IntTy);
212 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000213 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000214 if (checkArgCount(*this, TheCall, 1)) return true;
215 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000216 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000217 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000218 case Builtin::BI__sync_fetch_and_add_1:
219 case Builtin::BI__sync_fetch_and_add_2:
220 case Builtin::BI__sync_fetch_and_add_4:
221 case Builtin::BI__sync_fetch_and_add_8:
222 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000223 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000224 case Builtin::BI__sync_fetch_and_sub_1:
225 case Builtin::BI__sync_fetch_and_sub_2:
226 case Builtin::BI__sync_fetch_and_sub_4:
227 case Builtin::BI__sync_fetch_and_sub_8:
228 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000229 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000230 case Builtin::BI__sync_fetch_and_or_1:
231 case Builtin::BI__sync_fetch_and_or_2:
232 case Builtin::BI__sync_fetch_and_or_4:
233 case Builtin::BI__sync_fetch_and_or_8:
234 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000235 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000236 case Builtin::BI__sync_fetch_and_and_1:
237 case Builtin::BI__sync_fetch_and_and_2:
238 case Builtin::BI__sync_fetch_and_and_4:
239 case Builtin::BI__sync_fetch_and_and_8:
240 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000241 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000242 case Builtin::BI__sync_fetch_and_xor_1:
243 case Builtin::BI__sync_fetch_and_xor_2:
244 case Builtin::BI__sync_fetch_and_xor_4:
245 case Builtin::BI__sync_fetch_and_xor_8:
246 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000247 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000248 case Builtin::BI__sync_add_and_fetch_1:
249 case Builtin::BI__sync_add_and_fetch_2:
250 case Builtin::BI__sync_add_and_fetch_4:
251 case Builtin::BI__sync_add_and_fetch_8:
252 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000253 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000254 case Builtin::BI__sync_sub_and_fetch_1:
255 case Builtin::BI__sync_sub_and_fetch_2:
256 case Builtin::BI__sync_sub_and_fetch_4:
257 case Builtin::BI__sync_sub_and_fetch_8:
258 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000259 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000260 case Builtin::BI__sync_and_and_fetch_1:
261 case Builtin::BI__sync_and_and_fetch_2:
262 case Builtin::BI__sync_and_and_fetch_4:
263 case Builtin::BI__sync_and_and_fetch_8:
264 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000265 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000266 case Builtin::BI__sync_or_and_fetch_1:
267 case Builtin::BI__sync_or_and_fetch_2:
268 case Builtin::BI__sync_or_and_fetch_4:
269 case Builtin::BI__sync_or_and_fetch_8:
270 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000271 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000272 case Builtin::BI__sync_xor_and_fetch_1:
273 case Builtin::BI__sync_xor_and_fetch_2:
274 case Builtin::BI__sync_xor_and_fetch_4:
275 case Builtin::BI__sync_xor_and_fetch_8:
276 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000277 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000278 case Builtin::BI__sync_val_compare_and_swap_1:
279 case Builtin::BI__sync_val_compare_and_swap_2:
280 case Builtin::BI__sync_val_compare_and_swap_4:
281 case Builtin::BI__sync_val_compare_and_swap_8:
282 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000283 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000284 case Builtin::BI__sync_bool_compare_and_swap_1:
285 case Builtin::BI__sync_bool_compare_and_swap_2:
286 case Builtin::BI__sync_bool_compare_and_swap_4:
287 case Builtin::BI__sync_bool_compare_and_swap_8:
288 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000289 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000290 case Builtin::BI__sync_lock_test_and_set_1:
291 case Builtin::BI__sync_lock_test_and_set_2:
292 case Builtin::BI__sync_lock_test_and_set_4:
293 case Builtin::BI__sync_lock_test_and_set_8:
294 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000295 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000296 case Builtin::BI__sync_lock_release_1:
297 case Builtin::BI__sync_lock_release_2:
298 case Builtin::BI__sync_lock_release_4:
299 case Builtin::BI__sync_lock_release_8:
300 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000301 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000302 case Builtin::BI__sync_swap_1:
303 case Builtin::BI__sync_swap_2:
304 case Builtin::BI__sync_swap_4:
305 case Builtin::BI__sync_swap_8:
306 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000307 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000308#define BUILTIN(ID, TYPE, ATTRS)
309#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
310 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000311 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000312#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000313 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000314 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000315 return ExprError();
316 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000317 case Builtin::BI__builtin_addressof:
318 if (SemaBuiltinAddressof(*this, TheCall))
319 return ExprError();
320 break;
Richard Smith760520b2014-06-03 23:27:44 +0000321 case Builtin::BI__builtin_operator_new:
322 case Builtin::BI__builtin_operator_delete:
323 if (!getLangOpts().CPlusPlus) {
324 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
325 << (BuiltinID == Builtin::BI__builtin_operator_new
326 ? "__builtin_operator_new"
327 : "__builtin_operator_delete")
328 << "C++";
329 return ExprError();
330 }
331 // CodeGen assumes it can find the global new and delete to call,
332 // so ensure that they are declared.
333 DeclareGlobalNewDelete();
334 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000335 }
Richard Smith760520b2014-06-03 23:27:44 +0000336
Nate Begeman4904e322010-06-08 02:47:44 +0000337 // Since the target specific builtins for each arch overlap, only check those
338 // of the arch we are compiling for.
339 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000340 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000341 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000342 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000343 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000344 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000345 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
346 return ExprError();
347 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000348 case llvm::Triple::aarch64:
349 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000350 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000351 return ExprError();
352 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000353 case llvm::Triple::mips:
354 case llvm::Triple::mipsel:
355 case llvm::Triple::mips64:
356 case llvm::Triple::mips64el:
357 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
358 return ExprError();
359 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000360 case llvm::Triple::x86:
361 case llvm::Triple::x86_64:
362 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
363 return ExprError();
364 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000365 default:
366 break;
367 }
368 }
369
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000370 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000371}
372
Nate Begeman91e1fea2010-06-14 05:21:25 +0000373// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000374static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000375 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000376 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000377 switch (Type.getEltType()) {
378 case NeonTypeFlags::Int8:
379 case NeonTypeFlags::Poly8:
380 return shift ? 7 : (8 << IsQuad) - 1;
381 case NeonTypeFlags::Int16:
382 case NeonTypeFlags::Poly16:
383 return shift ? 15 : (4 << IsQuad) - 1;
384 case NeonTypeFlags::Int32:
385 return shift ? 31 : (2 << IsQuad) - 1;
386 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000387 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000388 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000389 case NeonTypeFlags::Poly128:
390 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000391 case NeonTypeFlags::Float16:
392 assert(!shift && "cannot shift float types!");
393 return (4 << IsQuad) - 1;
394 case NeonTypeFlags::Float32:
395 assert(!shift && "cannot shift float types!");
396 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000397 case NeonTypeFlags::Float64:
398 assert(!shift && "cannot shift float types!");
399 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000400 }
David Blaikie8a40f702012-01-17 06:56:22 +0000401 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000402}
403
Bob Wilsone4d77232011-11-08 05:04:11 +0000404/// getNeonEltType - Return the QualType corresponding to the elements of
405/// the vector type specified by the NeonTypeFlags. This is used to check
406/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000407static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000408 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000409 switch (Flags.getEltType()) {
410 case NeonTypeFlags::Int8:
411 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
412 case NeonTypeFlags::Int16:
413 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
414 case NeonTypeFlags::Int32:
415 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
416 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000417 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000418 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
419 else
420 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
421 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000422 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000423 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000424 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000425 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000427 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000428 case NeonTypeFlags::Poly128:
429 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000430 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000431 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000432 case NeonTypeFlags::Float32:
433 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000434 case NeonTypeFlags::Float64:
435 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000436 }
David Blaikie8a40f702012-01-17 06:56:22 +0000437 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000438}
439
Tim Northover12670412014-02-19 10:37:05 +0000440bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000441 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000442 uint64_t mask = 0;
443 unsigned TV = 0;
444 int PtrArgNum = -1;
445 bool HasConstPtr = false;
446 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000447#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000448#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000449#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000450 }
451
452 // For NEON intrinsics which are overloaded on vector element type, validate
453 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000454 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000455 if (mask) {
456 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
457 return true;
458
459 TV = Result.getLimitedValue(64);
460 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
461 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000462 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000463 }
464
465 if (PtrArgNum >= 0) {
466 // Check that pointer arguments have the specified type.
467 Expr *Arg = TheCall->getArg(PtrArgNum);
468 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
469 Arg = ICE->getSubExpr();
470 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
471 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000472
Tim Northovera2ee4332014-03-29 15:09:45 +0000473 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000474 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000475 bool IsInt64Long =
476 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
477 QualType EltTy =
478 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000479 if (HasConstPtr)
480 EltTy = EltTy.withConst();
481 QualType LHSTy = Context.getPointerType(EltTy);
482 AssignConvertType ConvTy;
483 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
484 if (RHS.isInvalid())
485 return true;
486 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
487 RHS.get(), AA_Assigning))
488 return true;
489 }
490
491 // For NEON intrinsics which take an immediate value as part of the
492 // instruction, range check them here.
493 unsigned i = 0, l = 0, u = 0;
494 switch (BuiltinID) {
495 default:
496 return false;
Tim Northover12670412014-02-19 10:37:05 +0000497#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000498#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000499#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000500 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000501
Richard Sandiford28940af2014-04-16 08:47:51 +0000502 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000503}
504
Tim Northovera2ee4332014-03-29 15:09:45 +0000505bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
506 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000507 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000508 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000509 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000510 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000511 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000512 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
513 BuiltinID == AArch64::BI__builtin_arm_strex ||
514 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000515 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000516 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000517 BuiltinID == ARM::BI__builtin_arm_ldaex ||
518 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
519 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000520
521 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
522
523 // Ensure that we have the proper number of arguments.
524 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
525 return true;
526
527 // Inspect the pointer argument of the atomic builtin. This should always be
528 // a pointer type, whose element is an integral scalar or pointer type.
529 // Because it is a pointer type, we don't have to worry about any implicit
530 // casts here.
531 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
532 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
533 if (PointerArgRes.isInvalid())
534 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000535 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000536
537 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
538 if (!pointerType) {
539 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
540 << PointerArg->getType() << PointerArg->getSourceRange();
541 return true;
542 }
543
544 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
545 // task is to insert the appropriate casts into the AST. First work out just
546 // what the appropriate type is.
547 QualType ValType = pointerType->getPointeeType();
548 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
549 if (IsLdrex)
550 AddrType.addConst();
551
552 // Issue a warning if the cast is dodgy.
553 CastKind CastNeeded = CK_NoOp;
554 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
555 CastNeeded = CK_BitCast;
556 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
557 << PointerArg->getType()
558 << Context.getPointerType(AddrType)
559 << AA_Passing << PointerArg->getSourceRange();
560 }
561
562 // Finally, do the cast and replace the argument with the corrected version.
563 AddrType = Context.getPointerType(AddrType);
564 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
565 if (PointerArgRes.isInvalid())
566 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000567 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000568
569 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
570
571 // In general, we allow ints, floats and pointers to be loaded and stored.
572 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
573 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
574 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
575 << PointerArg->getType() << PointerArg->getSourceRange();
576 return true;
577 }
578
579 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000580 if (Context.getTypeSize(ValType) > MaxWidth) {
581 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000582 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
583 << PointerArg->getType() << PointerArg->getSourceRange();
584 return true;
585 }
586
587 switch (ValType.getObjCLifetime()) {
588 case Qualifiers::OCL_None:
589 case Qualifiers::OCL_ExplicitNone:
590 // okay
591 break;
592
593 case Qualifiers::OCL_Weak:
594 case Qualifiers::OCL_Strong:
595 case Qualifiers::OCL_Autoreleasing:
596 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
597 << ValType << PointerArg->getSourceRange();
598 return true;
599 }
600
601
602 if (IsLdrex) {
603 TheCall->setType(ValType);
604 return false;
605 }
606
607 // Initialize the argument to be stored.
608 ExprResult ValArg = TheCall->getArg(0);
609 InitializedEntity Entity = InitializedEntity::InitializeParameter(
610 Context, ValType, /*consume*/ false);
611 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
612 if (ValArg.isInvalid())
613 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000614 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000615
616 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
617 // but the custom checker bypasses all default analysis.
618 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000619 return false;
620}
621
Nate Begeman4904e322010-06-08 02:47:44 +0000622bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000623 llvm::APSInt Result;
624
Tim Northover6aacd492013-07-16 09:47:53 +0000625 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000626 BuiltinID == ARM::BI__builtin_arm_ldaex ||
627 BuiltinID == ARM::BI__builtin_arm_strex ||
628 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000629 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000630 }
631
Yi Kong26d104a2014-08-13 19:18:14 +0000632 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
633 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
634 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
635 }
636
Tim Northover12670412014-02-19 10:37:05 +0000637 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
638 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000639
Yi Kong4efadfb2014-07-03 16:01:25 +0000640 // For intrinsics which take an immediate value as part of the instruction,
641 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000642 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000643 switch (BuiltinID) {
644 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000645 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
646 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000647 case ARM::BI__builtin_arm_vcvtr_f:
648 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000649 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000650 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000651 case ARM::BI__builtin_arm_isb:
652 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000653 }
Nate Begemand773fe62010-06-13 04:47:52 +0000654
Nate Begemanf568b072010-08-03 21:32:34 +0000655 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000656 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000657}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000658
Tim Northover573cbee2014-05-24 12:52:07 +0000659bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000660 CallExpr *TheCall) {
661 llvm::APSInt Result;
662
Tim Northover573cbee2014-05-24 12:52:07 +0000663 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000664 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
665 BuiltinID == AArch64::BI__builtin_arm_strex ||
666 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000667 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
668 }
669
Yi Konga5548432014-08-13 19:18:20 +0000670 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
671 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
672 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
673 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
674 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
675 }
676
Tim Northovera2ee4332014-03-29 15:09:45 +0000677 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
678 return true;
679
Yi Kong19a29ac2014-07-17 10:52:06 +0000680 // For intrinsics which take an immediate value as part of the instruction,
681 // range check them here.
682 unsigned i = 0, l = 0, u = 0;
683 switch (BuiltinID) {
684 default: return false;
685 case AArch64::BI__builtin_arm_dmb:
686 case AArch64::BI__builtin_arm_dsb:
687 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
688 }
689
Yi Kong19a29ac2014-07-17 10:52:06 +0000690 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000691}
692
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000693bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
694 unsigned i = 0, l = 0, u = 0;
695 switch (BuiltinID) {
696 default: return false;
697 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
698 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000699 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
700 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
701 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
702 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
703 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000704 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000705
Richard Sandiford28940af2014-04-16 08:47:51 +0000706 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000707}
708
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000709bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
710 switch (BuiltinID) {
711 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000712 // This is declared to take (const char*, int)
713 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000714 }
715 return false;
716}
717
Richard Smith55ce3522012-06-25 20:30:08 +0000718/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
719/// parameter with the FormatAttr's correct format_idx and firstDataArg.
720/// Returns true when the format fits the function and the FormatStringInfo has
721/// been populated.
722bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
723 FormatStringInfo *FSI) {
724 FSI->HasVAListArg = Format->getFirstArg() == 0;
725 FSI->FormatIdx = Format->getFormatIdx() - 1;
726 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000727
Richard Smith55ce3522012-06-25 20:30:08 +0000728 // The way the format attribute works in GCC, the implicit this argument
729 // of member functions is counted. However, it doesn't appear in our own
730 // lists, so decrement format_idx in that case.
731 if (IsCXXMember) {
732 if(FSI->FormatIdx == 0)
733 return false;
734 --FSI->FormatIdx;
735 if (FSI->FirstDataArg != 0)
736 --FSI->FirstDataArg;
737 }
738 return true;
739}
Mike Stump11289f42009-09-09 15:08:12 +0000740
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000741/// Checks if a the given expression evaluates to null.
742///
743/// \brief Returns true if the value evaluates to null.
744static bool CheckNonNullExpr(Sema &S,
745 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000746 // As a special case, transparent unions initialized with zero are
747 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000748 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000749 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
750 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000751 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000752 if (const InitListExpr *ILE =
753 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000754 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000755 }
756
757 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000758 return (!Expr->isValueDependent() &&
759 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
760 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000761}
762
763static void CheckNonNullArgument(Sema &S,
764 const Expr *ArgExpr,
765 SourceLocation CallSiteLoc) {
766 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000767 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
768}
769
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000770bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
771 FormatStringInfo FSI;
772 if ((GetFormatStringType(Format) == FST_NSString) &&
773 getFormatStringInfo(Format, false, &FSI)) {
774 Idx = FSI.FormatIdx;
775 return true;
776 }
777 return false;
778}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000779/// \brief Diagnose use of %s directive in an NSString which is being passed
780/// as formatting string to formatting method.
781static void
782DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
783 const NamedDecl *FDecl,
784 Expr **Args,
785 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000786 unsigned Idx = 0;
787 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000788 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
789 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000790 Idx = 2;
791 Format = true;
792 }
793 else
794 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
795 if (S.GetFormatNSStringIdx(I, Idx)) {
796 Format = true;
797 break;
798 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000799 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000800 if (!Format || NumArgs <= Idx)
801 return;
802 const Expr *FormatExpr = Args[Idx];
803 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
804 FormatExpr = CSCE->getSubExpr();
805 const StringLiteral *FormatString;
806 if (const ObjCStringLiteral *OSL =
807 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
808 FormatString = OSL->getString();
809 else
810 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
811 if (!FormatString)
812 return;
813 if (S.FormatStringHasSArg(FormatString)) {
814 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
815 << "%s" << 1 << 1;
816 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
817 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000818 }
819}
820
Ted Kremenek2bc73332014-01-17 06:24:43 +0000821static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000822 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000823 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000824 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000825 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000826 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000827 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000828 if (!NonNull->args_size()) {
829 // Easy case: all pointer arguments are nonnull.
830 for (const auto *Arg : Args)
831 if (S.isValidNonNullAttrType(Arg->getType()))
832 CheckNonNullArgument(S, Arg, CallSiteLoc);
833 return;
834 }
835
836 for (unsigned Val : NonNull->args()) {
837 if (Val >= Args.size())
838 continue;
839 if (NonNullArgs.empty())
840 NonNullArgs.resize(Args.size());
841 NonNullArgs.set(Val);
842 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000843 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000844
845 // Check the attributes on the parameters.
846 ArrayRef<ParmVarDecl*> parms;
847 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
848 parms = FD->parameters();
849 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
850 parms = MD->parameters();
851
Richard Smith588bd9b2014-08-27 04:59:42 +0000852 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000853 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000854 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000855 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000856 if (PVD->hasAttr<NonNullAttr>() ||
857 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
858 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000859 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000860
861 // In case this is a variadic call, check any remaining arguments.
862 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
863 if (NonNullArgs[ArgIndex])
864 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000865}
866
Richard Smith55ce3522012-06-25 20:30:08 +0000867/// Handles the checks for format strings, non-POD arguments to vararg
868/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000869void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
870 unsigned NumParams, bool IsMemberFunction,
871 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000872 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000873 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000874 if (CurContext->isDependentContext())
875 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000876
Ted Kremenekb8176da2010-09-09 04:33:05 +0000877 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000878 llvm::SmallBitVector CheckedVarArgs;
879 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000880 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000881 // Only create vector if there are format attributes.
882 CheckedVarArgs.resize(Args.size());
883
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000884 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000885 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000886 }
Richard Smithd7293d72013-08-05 18:49:43 +0000887 }
Richard Smith55ce3522012-06-25 20:30:08 +0000888
889 // Refuse POD arguments that weren't caught by the format string
890 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000891 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000892 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000893 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000894 if (const Expr *Arg = Args[ArgIdx]) {
895 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
896 checkVariadicArgument(Arg, CallType);
897 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000898 }
Richard Smithd7293d72013-08-05 18:49:43 +0000899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Richard Trieu41bc0992013-06-22 00:20:41 +0000901 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000902 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000903
Richard Trieu41bc0992013-06-22 00:20:41 +0000904 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000905 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
906 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000907 }
Richard Smith55ce3522012-06-25 20:30:08 +0000908}
909
910/// CheckConstructorCall - Check a constructor call for correctness and safety
911/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000912void Sema::CheckConstructorCall(FunctionDecl *FDecl,
913 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000914 const FunctionProtoType *Proto,
915 SourceLocation Loc) {
916 VariadicCallType CallType =
917 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000918 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000919 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
920}
921
922/// CheckFunctionCall - Check a direct function call for various correctness
923/// and safety properties not strictly enforced by the C type system.
924bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
925 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000926 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
927 isa<CXXMethodDecl>(FDecl);
928 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
929 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000930 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
931 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000932 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000933 Expr** Args = TheCall->getArgs();
934 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000935 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000936 // If this is a call to a member operator, hide the first argument
937 // from checkCall.
938 // FIXME: Our choice of AST representation here is less than ideal.
939 ++Args;
940 --NumArgs;
941 }
Craig Topper8c2a2a02014-08-30 16:55:39 +0000942 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000943 IsMemberFunction, TheCall->getRParenLoc(),
944 TheCall->getCallee()->getSourceRange(), CallType);
945
946 IdentifierInfo *FnInfo = FDecl->getIdentifier();
947 // None of the checks below are needed for functions that don't have
948 // simple names (e.g., C++ conversion functions).
949 if (!FnInfo)
950 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000951
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000952 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000953 if (getLangOpts().ObjC1)
954 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000955
Anna Zaks22122702012-01-17 00:37:07 +0000956 unsigned CMId = FDecl->getMemoryFunctionKind();
957 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000958 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000959
Anna Zaks201d4892012-01-13 21:52:01 +0000960 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000961 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000962 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000963 else if (CMId == Builtin::BIstrncat)
964 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000965 else
Anna Zaks22122702012-01-17 00:37:07 +0000966 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000967
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000968 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000969}
970
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000971bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000972 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000973 VariadicCallType CallType =
974 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000975
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000976 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000977 /*IsMemberFunction=*/false,
978 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000979
980 return false;
981}
982
Richard Trieu664c4c62013-06-20 21:03:13 +0000983bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
984 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000985 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
986 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000987 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000989 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000990 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000991 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000992
Richard Trieu664c4c62013-06-20 21:03:13 +0000993 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000994 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000995 CallType = VariadicDoesNotApply;
996 } else if (Ty->isBlockPointerType()) {
997 CallType = VariadicBlock;
998 } else { // Ty->isFunctionPointerType()
999 CallType = VariadicFunction;
1000 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001001 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001002
Craig Topper8c2a2a02014-08-30 16:55:39 +00001003 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1004 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001005 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001006 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001007
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001008 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001009}
1010
Richard Trieu41bc0992013-06-22 00:20:41 +00001011/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1012/// such as function pointers returned from functions.
1013bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001014 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001015 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001016 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001017
Craig Topperc3ec1492014-05-26 06:22:03 +00001018 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001019 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001020 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001021 TheCall->getCallee()->getSourceRange(), CallType);
1022
1023 return false;
1024}
1025
Tim Northovere94a34c2014-03-11 10:49:14 +00001026static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1027 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1028 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1029 return false;
1030
1031 switch (Op) {
1032 case AtomicExpr::AO__c11_atomic_init:
1033 llvm_unreachable("There is no ordering argument for an init");
1034
1035 case AtomicExpr::AO__c11_atomic_load:
1036 case AtomicExpr::AO__atomic_load_n:
1037 case AtomicExpr::AO__atomic_load:
1038 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1039 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1040
1041 case AtomicExpr::AO__c11_atomic_store:
1042 case AtomicExpr::AO__atomic_store:
1043 case AtomicExpr::AO__atomic_store_n:
1044 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1045 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1046 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1047
1048 default:
1049 return true;
1050 }
1051}
1052
Richard Smithfeea8832012-04-12 05:08:17 +00001053ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1054 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001055 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1056 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001057
Richard Smithfeea8832012-04-12 05:08:17 +00001058 // All these operations take one of the following forms:
1059 enum {
1060 // C __c11_atomic_init(A *, C)
1061 Init,
1062 // C __c11_atomic_load(A *, int)
1063 Load,
1064 // void __atomic_load(A *, CP, int)
1065 Copy,
1066 // C __c11_atomic_add(A *, M, int)
1067 Arithmetic,
1068 // C __atomic_exchange_n(A *, CP, int)
1069 Xchg,
1070 // void __atomic_exchange(A *, C *, CP, int)
1071 GNUXchg,
1072 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1073 C11CmpXchg,
1074 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1075 GNUCmpXchg
1076 } Form = Init;
1077 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1078 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1079 // where:
1080 // C is an appropriate type,
1081 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1082 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1083 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1084 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001085
Richard Smithfeea8832012-04-12 05:08:17 +00001086 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1087 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1088 && "need to update code for modified C11 atomics");
1089 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1090 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1091 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1092 Op == AtomicExpr::AO__atomic_store_n ||
1093 Op == AtomicExpr::AO__atomic_exchange_n ||
1094 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1095 bool IsAddSub = false;
1096
1097 switch (Op) {
1098 case AtomicExpr::AO__c11_atomic_init:
1099 Form = Init;
1100 break;
1101
1102 case AtomicExpr::AO__c11_atomic_load:
1103 case AtomicExpr::AO__atomic_load_n:
1104 Form = Load;
1105 break;
1106
1107 case AtomicExpr::AO__c11_atomic_store:
1108 case AtomicExpr::AO__atomic_load:
1109 case AtomicExpr::AO__atomic_store:
1110 case AtomicExpr::AO__atomic_store_n:
1111 Form = Copy;
1112 break;
1113
1114 case AtomicExpr::AO__c11_atomic_fetch_add:
1115 case AtomicExpr::AO__c11_atomic_fetch_sub:
1116 case AtomicExpr::AO__atomic_fetch_add:
1117 case AtomicExpr::AO__atomic_fetch_sub:
1118 case AtomicExpr::AO__atomic_add_fetch:
1119 case AtomicExpr::AO__atomic_sub_fetch:
1120 IsAddSub = true;
1121 // Fall through.
1122 case AtomicExpr::AO__c11_atomic_fetch_and:
1123 case AtomicExpr::AO__c11_atomic_fetch_or:
1124 case AtomicExpr::AO__c11_atomic_fetch_xor:
1125 case AtomicExpr::AO__atomic_fetch_and:
1126 case AtomicExpr::AO__atomic_fetch_or:
1127 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001128 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001129 case AtomicExpr::AO__atomic_and_fetch:
1130 case AtomicExpr::AO__atomic_or_fetch:
1131 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001132 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001133 Form = Arithmetic;
1134 break;
1135
1136 case AtomicExpr::AO__c11_atomic_exchange:
1137 case AtomicExpr::AO__atomic_exchange_n:
1138 Form = Xchg;
1139 break;
1140
1141 case AtomicExpr::AO__atomic_exchange:
1142 Form = GNUXchg;
1143 break;
1144
1145 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1146 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1147 Form = C11CmpXchg;
1148 break;
1149
1150 case AtomicExpr::AO__atomic_compare_exchange:
1151 case AtomicExpr::AO__atomic_compare_exchange_n:
1152 Form = GNUCmpXchg;
1153 break;
1154 }
1155
1156 // Check we have the right number of arguments.
1157 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001158 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001159 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001160 << TheCall->getCallee()->getSourceRange();
1161 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001162 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1163 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001164 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001165 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001166 << TheCall->getCallee()->getSourceRange();
1167 return ExprError();
1168 }
1169
Richard Smithfeea8832012-04-12 05:08:17 +00001170 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001171 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001172 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1173 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1174 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001175 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001176 << Ptr->getType() << Ptr->getSourceRange();
1177 return ExprError();
1178 }
1179
Richard Smithfeea8832012-04-12 05:08:17 +00001180 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1181 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1182 QualType ValType = AtomTy; // 'C'
1183 if (IsC11) {
1184 if (!AtomTy->isAtomicType()) {
1185 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1186 << Ptr->getType() << Ptr->getSourceRange();
1187 return ExprError();
1188 }
Richard Smithe00921a2012-09-15 06:09:58 +00001189 if (AtomTy.isConstQualified()) {
1190 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1191 << Ptr->getType() << Ptr->getSourceRange();
1192 return ExprError();
1193 }
Richard Smithfeea8832012-04-12 05:08:17 +00001194 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001195 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001196
Richard Smithfeea8832012-04-12 05:08:17 +00001197 // For an arithmetic operation, the implied arithmetic must be well-formed.
1198 if (Form == Arithmetic) {
1199 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1200 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1201 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1202 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1203 return ExprError();
1204 }
1205 if (!IsAddSub && !ValType->isIntegerType()) {
1206 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1207 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1208 return ExprError();
1209 }
1210 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1211 // For __atomic_*_n operations, the value type must be a scalar integral or
1212 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001213 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001214 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1215 return ExprError();
1216 }
1217
Eli Friedmanaa769812013-09-11 03:49:34 +00001218 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1219 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001220 // For GNU atomics, require a trivially-copyable type. This is not part of
1221 // the GNU atomics specification, but we enforce it for sanity.
1222 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001223 << Ptr->getType() << Ptr->getSourceRange();
1224 return ExprError();
1225 }
1226
Richard Smithfeea8832012-04-12 05:08:17 +00001227 // FIXME: For any builtin other than a load, the ValType must not be
1228 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001229
1230 switch (ValType.getObjCLifetime()) {
1231 case Qualifiers::OCL_None:
1232 case Qualifiers::OCL_ExplicitNone:
1233 // okay
1234 break;
1235
1236 case Qualifiers::OCL_Weak:
1237 case Qualifiers::OCL_Strong:
1238 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001239 // FIXME: Can this happen? By this point, ValType should be known
1240 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001241 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1242 << ValType << Ptr->getSourceRange();
1243 return ExprError();
1244 }
1245
1246 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001247 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001248 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001249 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001250 ResultType = Context.BoolTy;
1251
Richard Smithfeea8832012-04-12 05:08:17 +00001252 // The type of a parameter passed 'by value'. In the GNU atomics, such
1253 // arguments are actually passed as pointers.
1254 QualType ByValType = ValType; // 'CP'
1255 if (!IsC11 && !IsN)
1256 ByValType = Ptr->getType();
1257
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001258 // The first argument --- the pointer --- has a fixed type; we
1259 // deduce the types of the rest of the arguments accordingly. Walk
1260 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001261 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001262 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001263 if (i < NumVals[Form] + 1) {
1264 switch (i) {
1265 case 1:
1266 // The second argument is the non-atomic operand. For arithmetic, this
1267 // is always passed by value, and for a compare_exchange it is always
1268 // passed by address. For the rest, GNU uses by-address and C11 uses
1269 // by-value.
1270 assert(Form != Load);
1271 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1272 Ty = ValType;
1273 else if (Form == Copy || Form == Xchg)
1274 Ty = ByValType;
1275 else if (Form == Arithmetic)
1276 Ty = Context.getPointerDiffType();
1277 else
1278 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1279 break;
1280 case 2:
1281 // The third argument to compare_exchange / GNU exchange is a
1282 // (pointer to a) desired value.
1283 Ty = ByValType;
1284 break;
1285 case 3:
1286 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1287 Ty = Context.BoolTy;
1288 break;
1289 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001290 } else {
1291 // The order(s) are always converted to int.
1292 Ty = Context.IntTy;
1293 }
Richard Smithfeea8832012-04-12 05:08:17 +00001294
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001295 InitializedEntity Entity =
1296 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001297 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001298 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1299 if (Arg.isInvalid())
1300 return true;
1301 TheCall->setArg(i, Arg.get());
1302 }
1303
Richard Smithfeea8832012-04-12 05:08:17 +00001304 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001305 SmallVector<Expr*, 5> SubExprs;
1306 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001307 switch (Form) {
1308 case Init:
1309 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001310 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001311 break;
1312 case Load:
1313 SubExprs.push_back(TheCall->getArg(1)); // Order
1314 break;
1315 case Copy:
1316 case Arithmetic:
1317 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001318 SubExprs.push_back(TheCall->getArg(2)); // Order
1319 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001320 break;
1321 case GNUXchg:
1322 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1323 SubExprs.push_back(TheCall->getArg(3)); // Order
1324 SubExprs.push_back(TheCall->getArg(1)); // Val1
1325 SubExprs.push_back(TheCall->getArg(2)); // Val2
1326 break;
1327 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001328 SubExprs.push_back(TheCall->getArg(3)); // Order
1329 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001330 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001331 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001332 break;
1333 case GNUCmpXchg:
1334 SubExprs.push_back(TheCall->getArg(4)); // Order
1335 SubExprs.push_back(TheCall->getArg(1)); // Val1
1336 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1337 SubExprs.push_back(TheCall->getArg(2)); // Val2
1338 SubExprs.push_back(TheCall->getArg(3)); // Weak
1339 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001340 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001341
1342 if (SubExprs.size() >= 2 && Form != Init) {
1343 llvm::APSInt Result(32);
1344 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1345 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001346 Diag(SubExprs[1]->getLocStart(),
1347 diag::warn_atomic_op_has_invalid_memory_order)
1348 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001349 }
1350
Fariborz Jahanian615de762013-05-28 17:37:39 +00001351 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1352 SubExprs, ResultType, Op,
1353 TheCall->getRParenLoc());
1354
1355 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1356 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1357 Context.AtomicUsesUnsupportedLibcall(AE))
1358 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1359 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001360
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001361 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001362}
1363
1364
John McCall29ad95b2011-08-27 01:09:30 +00001365/// checkBuiltinArgument - Given a call to a builtin function, perform
1366/// normal type-checking on the given argument, updating the call in
1367/// place. This is useful when a builtin function requires custom
1368/// type-checking for some of its arguments but not necessarily all of
1369/// them.
1370///
1371/// Returns true on error.
1372static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1373 FunctionDecl *Fn = E->getDirectCallee();
1374 assert(Fn && "builtin call without direct callee!");
1375
1376 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1377 InitializedEntity Entity =
1378 InitializedEntity::InitializeParameter(S.Context, Param);
1379
1380 ExprResult Arg = E->getArg(0);
1381 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1382 if (Arg.isInvalid())
1383 return true;
1384
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001385 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001386 return false;
1387}
1388
Chris Lattnerdc046542009-05-08 06:58:22 +00001389/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1390/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1391/// type of its first argument. The main ActOnCallExpr routines have already
1392/// promoted the types of arguments because all of these calls are prototyped as
1393/// void(...).
1394///
1395/// This function goes through and does final semantic checking for these
1396/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001397ExprResult
1398Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001399 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001400 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1401 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1402
1403 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001404 if (TheCall->getNumArgs() < 1) {
1405 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1406 << 0 << 1 << TheCall->getNumArgs()
1407 << TheCall->getCallee()->getSourceRange();
1408 return ExprError();
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Chris Lattnerdc046542009-05-08 06:58:22 +00001411 // Inspect the first argument of the atomic builtin. This should always be
1412 // a pointer type, whose element is an integral scalar or pointer type.
1413 // Because it is a pointer type, we don't have to worry about any implicit
1414 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001415 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001416 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001417 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1418 if (FirstArgResult.isInvalid())
1419 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001420 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001421 TheCall->setArg(0, FirstArg);
1422
John McCall31168b02011-06-15 23:02:42 +00001423 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1424 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001425 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1426 << FirstArg->getType() << FirstArg->getSourceRange();
1427 return ExprError();
1428 }
Mike Stump11289f42009-09-09 15:08:12 +00001429
John McCall31168b02011-06-15 23:02:42 +00001430 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001431 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001432 !ValType->isBlockPointerType()) {
1433 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1434 << FirstArg->getType() << FirstArg->getSourceRange();
1435 return ExprError();
1436 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001437
John McCall31168b02011-06-15 23:02:42 +00001438 switch (ValType.getObjCLifetime()) {
1439 case Qualifiers::OCL_None:
1440 case Qualifiers::OCL_ExplicitNone:
1441 // okay
1442 break;
1443
1444 case Qualifiers::OCL_Weak:
1445 case Qualifiers::OCL_Strong:
1446 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001447 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001448 << ValType << FirstArg->getSourceRange();
1449 return ExprError();
1450 }
1451
John McCallb50451a2011-10-05 07:41:44 +00001452 // Strip any qualifiers off ValType.
1453 ValType = ValType.getUnqualifiedType();
1454
Chandler Carruth3973af72010-07-18 20:54:12 +00001455 // The majority of builtins return a value, but a few have special return
1456 // types, so allow them to override appropriately below.
1457 QualType ResultType = ValType;
1458
Chris Lattnerdc046542009-05-08 06:58:22 +00001459 // We need to figure out which concrete builtin this maps onto. For example,
1460 // __sync_fetch_and_add with a 2 byte object turns into
1461 // __sync_fetch_and_add_2.
1462#define BUILTIN_ROW(x) \
1463 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1464 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
Chris Lattnerdc046542009-05-08 06:58:22 +00001466 static const unsigned BuiltinIndices[][5] = {
1467 BUILTIN_ROW(__sync_fetch_and_add),
1468 BUILTIN_ROW(__sync_fetch_and_sub),
1469 BUILTIN_ROW(__sync_fetch_and_or),
1470 BUILTIN_ROW(__sync_fetch_and_and),
1471 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattnerdc046542009-05-08 06:58:22 +00001473 BUILTIN_ROW(__sync_add_and_fetch),
1474 BUILTIN_ROW(__sync_sub_and_fetch),
1475 BUILTIN_ROW(__sync_and_and_fetch),
1476 BUILTIN_ROW(__sync_or_and_fetch),
1477 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001478
Chris Lattnerdc046542009-05-08 06:58:22 +00001479 BUILTIN_ROW(__sync_val_compare_and_swap),
1480 BUILTIN_ROW(__sync_bool_compare_and_swap),
1481 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001482 BUILTIN_ROW(__sync_lock_release),
1483 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001484 };
Mike Stump11289f42009-09-09 15:08:12 +00001485#undef BUILTIN_ROW
1486
Chris Lattnerdc046542009-05-08 06:58:22 +00001487 // Determine the index of the size.
1488 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001489 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001490 case 1: SizeIndex = 0; break;
1491 case 2: SizeIndex = 1; break;
1492 case 4: SizeIndex = 2; break;
1493 case 8: SizeIndex = 3; break;
1494 case 16: SizeIndex = 4; break;
1495 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001496 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1497 << FirstArg->getType() << FirstArg->getSourceRange();
1498 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500
Chris Lattnerdc046542009-05-08 06:58:22 +00001501 // Each of these builtins has one pointer argument, followed by some number of
1502 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1503 // that we ignore. Find out which row of BuiltinIndices to read from as well
1504 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001505 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001506 unsigned BuiltinIndex, NumFixed = 1;
1507 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001508 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001509 case Builtin::BI__sync_fetch_and_add:
1510 case Builtin::BI__sync_fetch_and_add_1:
1511 case Builtin::BI__sync_fetch_and_add_2:
1512 case Builtin::BI__sync_fetch_and_add_4:
1513 case Builtin::BI__sync_fetch_and_add_8:
1514 case Builtin::BI__sync_fetch_and_add_16:
1515 BuiltinIndex = 0;
1516 break;
1517
1518 case Builtin::BI__sync_fetch_and_sub:
1519 case Builtin::BI__sync_fetch_and_sub_1:
1520 case Builtin::BI__sync_fetch_and_sub_2:
1521 case Builtin::BI__sync_fetch_and_sub_4:
1522 case Builtin::BI__sync_fetch_and_sub_8:
1523 case Builtin::BI__sync_fetch_and_sub_16:
1524 BuiltinIndex = 1;
1525 break;
1526
1527 case Builtin::BI__sync_fetch_and_or:
1528 case Builtin::BI__sync_fetch_and_or_1:
1529 case Builtin::BI__sync_fetch_and_or_2:
1530 case Builtin::BI__sync_fetch_and_or_4:
1531 case Builtin::BI__sync_fetch_and_or_8:
1532 case Builtin::BI__sync_fetch_and_or_16:
1533 BuiltinIndex = 2;
1534 break;
1535
1536 case Builtin::BI__sync_fetch_and_and:
1537 case Builtin::BI__sync_fetch_and_and_1:
1538 case Builtin::BI__sync_fetch_and_and_2:
1539 case Builtin::BI__sync_fetch_and_and_4:
1540 case Builtin::BI__sync_fetch_and_and_8:
1541 case Builtin::BI__sync_fetch_and_and_16:
1542 BuiltinIndex = 3;
1543 break;
Mike Stump11289f42009-09-09 15:08:12 +00001544
Douglas Gregor73722482011-11-28 16:30:08 +00001545 case Builtin::BI__sync_fetch_and_xor:
1546 case Builtin::BI__sync_fetch_and_xor_1:
1547 case Builtin::BI__sync_fetch_and_xor_2:
1548 case Builtin::BI__sync_fetch_and_xor_4:
1549 case Builtin::BI__sync_fetch_and_xor_8:
1550 case Builtin::BI__sync_fetch_and_xor_16:
1551 BuiltinIndex = 4;
1552 break;
1553
1554 case Builtin::BI__sync_add_and_fetch:
1555 case Builtin::BI__sync_add_and_fetch_1:
1556 case Builtin::BI__sync_add_and_fetch_2:
1557 case Builtin::BI__sync_add_and_fetch_4:
1558 case Builtin::BI__sync_add_and_fetch_8:
1559 case Builtin::BI__sync_add_and_fetch_16:
1560 BuiltinIndex = 5;
1561 break;
1562
1563 case Builtin::BI__sync_sub_and_fetch:
1564 case Builtin::BI__sync_sub_and_fetch_1:
1565 case Builtin::BI__sync_sub_and_fetch_2:
1566 case Builtin::BI__sync_sub_and_fetch_4:
1567 case Builtin::BI__sync_sub_and_fetch_8:
1568 case Builtin::BI__sync_sub_and_fetch_16:
1569 BuiltinIndex = 6;
1570 break;
1571
1572 case Builtin::BI__sync_and_and_fetch:
1573 case Builtin::BI__sync_and_and_fetch_1:
1574 case Builtin::BI__sync_and_and_fetch_2:
1575 case Builtin::BI__sync_and_and_fetch_4:
1576 case Builtin::BI__sync_and_and_fetch_8:
1577 case Builtin::BI__sync_and_and_fetch_16:
1578 BuiltinIndex = 7;
1579 break;
1580
1581 case Builtin::BI__sync_or_and_fetch:
1582 case Builtin::BI__sync_or_and_fetch_1:
1583 case Builtin::BI__sync_or_and_fetch_2:
1584 case Builtin::BI__sync_or_and_fetch_4:
1585 case Builtin::BI__sync_or_and_fetch_8:
1586 case Builtin::BI__sync_or_and_fetch_16:
1587 BuiltinIndex = 8;
1588 break;
1589
1590 case Builtin::BI__sync_xor_and_fetch:
1591 case Builtin::BI__sync_xor_and_fetch_1:
1592 case Builtin::BI__sync_xor_and_fetch_2:
1593 case Builtin::BI__sync_xor_and_fetch_4:
1594 case Builtin::BI__sync_xor_and_fetch_8:
1595 case Builtin::BI__sync_xor_and_fetch_16:
1596 BuiltinIndex = 9;
1597 break;
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattnerdc046542009-05-08 06:58:22 +00001599 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001600 case Builtin::BI__sync_val_compare_and_swap_1:
1601 case Builtin::BI__sync_val_compare_and_swap_2:
1602 case Builtin::BI__sync_val_compare_and_swap_4:
1603 case Builtin::BI__sync_val_compare_and_swap_8:
1604 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001605 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001606 NumFixed = 2;
1607 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001608
Chris Lattnerdc046542009-05-08 06:58:22 +00001609 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001610 case Builtin::BI__sync_bool_compare_and_swap_1:
1611 case Builtin::BI__sync_bool_compare_and_swap_2:
1612 case Builtin::BI__sync_bool_compare_and_swap_4:
1613 case Builtin::BI__sync_bool_compare_and_swap_8:
1614 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001615 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001616 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001617 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001618 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001619
1620 case Builtin::BI__sync_lock_test_and_set:
1621 case Builtin::BI__sync_lock_test_and_set_1:
1622 case Builtin::BI__sync_lock_test_and_set_2:
1623 case Builtin::BI__sync_lock_test_and_set_4:
1624 case Builtin::BI__sync_lock_test_and_set_8:
1625 case Builtin::BI__sync_lock_test_and_set_16:
1626 BuiltinIndex = 12;
1627 break;
1628
Chris Lattnerdc046542009-05-08 06:58:22 +00001629 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001630 case Builtin::BI__sync_lock_release_1:
1631 case Builtin::BI__sync_lock_release_2:
1632 case Builtin::BI__sync_lock_release_4:
1633 case Builtin::BI__sync_lock_release_8:
1634 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001635 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001636 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001637 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001638 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001639
1640 case Builtin::BI__sync_swap:
1641 case Builtin::BI__sync_swap_1:
1642 case Builtin::BI__sync_swap_2:
1643 case Builtin::BI__sync_swap_4:
1644 case Builtin::BI__sync_swap_8:
1645 case Builtin::BI__sync_swap_16:
1646 BuiltinIndex = 14;
1647 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001648 }
Mike Stump11289f42009-09-09 15:08:12 +00001649
Chris Lattnerdc046542009-05-08 06:58:22 +00001650 // Now that we know how many fixed arguments we expect, first check that we
1651 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001652 if (TheCall->getNumArgs() < 1+NumFixed) {
1653 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1654 << 0 << 1+NumFixed << TheCall->getNumArgs()
1655 << TheCall->getCallee()->getSourceRange();
1656 return ExprError();
1657 }
Mike Stump11289f42009-09-09 15:08:12 +00001658
Chris Lattner5b9241b2009-05-08 15:36:58 +00001659 // Get the decl for the concrete builtin from this, we can tell what the
1660 // concrete integer type we should convert to is.
1661 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1662 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001663 FunctionDecl *NewBuiltinDecl;
1664 if (NewBuiltinID == BuiltinID)
1665 NewBuiltinDecl = FDecl;
1666 else {
1667 // Perform builtin lookup to avoid redeclaring it.
1668 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1669 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1670 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1671 assert(Res.getFoundDecl());
1672 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001673 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001674 return ExprError();
1675 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001676
John McCallcf142162010-08-07 06:22:56 +00001677 // The first argument --- the pointer --- has a fixed type; we
1678 // deduce the types of the rest of the arguments accordingly. Walk
1679 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001680 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001681 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattnerdc046542009-05-08 06:58:22 +00001683 // GCC does an implicit conversion to the pointer or integer ValType. This
1684 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001685 // Initialize the argument.
1686 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1687 ValType, /*consume*/ false);
1688 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001689 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001690 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattnerdc046542009-05-08 06:58:22 +00001692 // Okay, we have something that *can* be converted to the right type. Check
1693 // to see if there is a potentially weird extension going on here. This can
1694 // happen when you do an atomic operation on something like an char* and
1695 // pass in 42. The 42 gets converted to char. This is even more strange
1696 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001697 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001698 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001701 ASTContext& Context = this->getASTContext();
1702
1703 // Create a new DeclRefExpr to refer to the new decl.
1704 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1705 Context,
1706 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001707 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001708 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001709 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001710 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001711 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001712 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerdc046542009-05-08 06:58:22 +00001714 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001715 // FIXME: This loses syntactic information.
1716 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1717 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1718 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001719 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001721 // Change the result type of the call to match the original value type. This
1722 // is arbitrary, but the codegen for these builtins ins design to handle it
1723 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001724 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001725
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001726 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001727}
1728
Chris Lattner6436fb62009-02-18 06:01:06 +00001729/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001730/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001731/// Note: It might also make sense to do the UTF-16 conversion here (would
1732/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001733bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001734 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001735 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1736
Douglas Gregorfb65e592011-07-27 05:40:30 +00001737 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001738 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1739 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001740 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001743 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001744 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001745 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001746 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001747 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001748 UTF16 *ToPtr = &ToBuf[0];
1749
1750 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1751 &ToPtr, ToPtr + NumBytes,
1752 strictConversion);
1753 // Check for conversion failure.
1754 if (Result != conversionOK)
1755 Diag(Arg->getLocStart(),
1756 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1757 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001758 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001759}
1760
Chris Lattnere202e6a2007-12-20 00:05:45 +00001761/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1762/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001763bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1764 Expr *Fn = TheCall->getCallee();
1765 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001766 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001767 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001768 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1769 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001770 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001771 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001772 return true;
1773 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001774
1775 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001776 return Diag(TheCall->getLocEnd(),
1777 diag::err_typecheck_call_too_few_args_at_least)
1778 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001779 }
1780
John McCall29ad95b2011-08-27 01:09:30 +00001781 // Type-check the first argument normally.
1782 if (checkBuiltinArgument(*this, TheCall, 0))
1783 return true;
1784
Chris Lattnere202e6a2007-12-20 00:05:45 +00001785 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001786 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001787 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001788 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001789 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001790 else if (FunctionDecl *FD = getCurFunctionDecl())
1791 isVariadic = FD->isVariadic();
1792 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001793 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattnere202e6a2007-12-20 00:05:45 +00001795 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001796 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1797 return true;
1798 }
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattner43be2e62007-12-19 23:59:04 +00001800 // Verify that the second argument to the builtin is the last argument of the
1801 // current function or method.
1802 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001803 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001804
Nico Weber9eea7642013-05-24 23:31:57 +00001805 // These are valid if SecondArgIsLastNamedArgument is false after the next
1806 // block.
1807 QualType Type;
1808 SourceLocation ParamLoc;
1809
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001810 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1811 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001812 // FIXME: This isn't correct for methods (results in bogus warning).
1813 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001814 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001815 if (CurBlock)
1816 LastArg = *(CurBlock->TheDecl->param_end()-1);
1817 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001818 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001819 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001820 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001821 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001822
1823 Type = PV->getType();
1824 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001825 }
1826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
Chris Lattner43be2e62007-12-19 23:59:04 +00001828 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001829 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001830 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001831 else if (Type->isReferenceType()) {
1832 Diag(Arg->getLocStart(),
1833 diag::warn_va_start_of_reference_type_is_undefined);
1834 Diag(ParamLoc, diag::note_parameter_type) << Type;
1835 }
1836
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001837 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001838 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001839}
Chris Lattner43be2e62007-12-19 23:59:04 +00001840
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001841bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1842 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1843 // const char *named_addr);
1844
1845 Expr *Func = Call->getCallee();
1846
1847 if (Call->getNumArgs() < 3)
1848 return Diag(Call->getLocEnd(),
1849 diag::err_typecheck_call_too_few_args_at_least)
1850 << 0 /*function call*/ << 3 << Call->getNumArgs();
1851
1852 // Determine whether the current function is variadic or not.
1853 bool IsVariadic;
1854 if (BlockScopeInfo *CurBlock = getCurBlock())
1855 IsVariadic = CurBlock->TheDecl->isVariadic();
1856 else if (FunctionDecl *FD = getCurFunctionDecl())
1857 IsVariadic = FD->isVariadic();
1858 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1859 IsVariadic = MD->isVariadic();
1860 else
1861 llvm_unreachable("unexpected statement type");
1862
1863 if (!IsVariadic) {
1864 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1865 return true;
1866 }
1867
1868 // Type-check the first argument normally.
1869 if (checkBuiltinArgument(*this, Call, 0))
1870 return true;
1871
1872 static const struct {
1873 unsigned ArgNo;
1874 QualType Type;
1875 } ArgumentTypes[] = {
1876 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1877 { 2, Context.getSizeType() },
1878 };
1879
1880 for (const auto &AT : ArgumentTypes) {
1881 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1882 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1883 continue;
1884 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1885 << Arg->getType() << AT.Type << 1 /* different class */
1886 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1887 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1888 }
1889
1890 return false;
1891}
1892
Chris Lattner2da14fb2007-12-20 00:26:33 +00001893/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1894/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001895bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1896 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001897 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001898 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001899 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001900 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001901 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001902 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001903 << SourceRange(TheCall->getArg(2)->getLocStart(),
1904 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001905
John Wiegley01296292011-04-08 18:41:53 +00001906 ExprResult OrigArg0 = TheCall->getArg(0);
1907 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001908
Chris Lattner2da14fb2007-12-20 00:26:33 +00001909 // Do standard promotions between the two arguments, returning their common
1910 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001911 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001912 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1913 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001914
1915 // Make sure any conversions are pushed back into the call; this is
1916 // type safe since unordered compare builtins are declared as "_Bool
1917 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001918 TheCall->setArg(0, OrigArg0.get());
1919 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001920
John Wiegley01296292011-04-08 18:41:53 +00001921 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001922 return false;
1923
Chris Lattner2da14fb2007-12-20 00:26:33 +00001924 // If the common type isn't a real floating type, then the arguments were
1925 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001926 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001927 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001928 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001929 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1930 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001931
Chris Lattner2da14fb2007-12-20 00:26:33 +00001932 return false;
1933}
1934
Benjamin Kramer634fc102010-02-15 22:42:31 +00001935/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1936/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001937/// to check everything. We expect the last argument to be a floating point
1938/// value.
1939bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1940 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001941 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001942 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001943 if (TheCall->getNumArgs() > NumArgs)
1944 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001945 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001946 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001947 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001948 (*(TheCall->arg_end()-1))->getLocEnd());
1949
Benjamin Kramer64aae502010-02-16 10:07:31 +00001950 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Eli Friedman7e4faac2009-08-31 20:06:00 +00001952 if (OrigArg->isTypeDependent())
1953 return false;
1954
Chris Lattner68784ef2010-05-06 05:50:07 +00001955 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001956 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001957 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001958 diag::err_typecheck_call_invalid_unary_fp)
1959 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001960
Chris Lattner68784ef2010-05-06 05:50:07 +00001961 // If this is an implicit conversion from float -> double, remove it.
1962 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1963 Expr *CastArg = Cast->getSubExpr();
1964 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1965 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1966 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001967 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001968 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001969 }
1970 }
1971
Eli Friedman7e4faac2009-08-31 20:06:00 +00001972 return false;
1973}
1974
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001975/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1976// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001977ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001978 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001979 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001980 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001981 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1982 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001983
Nate Begemana0110022010-06-08 00:16:34 +00001984 // Determine which of the following types of shufflevector we're checking:
1985 // 1) unary, vector mask: (lhs, mask)
1986 // 2) binary, vector mask: (lhs, rhs, mask)
1987 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1988 QualType resType = TheCall->getArg(0)->getType();
1989 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001990
Douglas Gregorc25f7662009-05-19 22:10:17 +00001991 if (!TheCall->getArg(0)->isTypeDependent() &&
1992 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001993 QualType LHSType = TheCall->getArg(0)->getType();
1994 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001995
Craig Topperbaca3892013-07-29 06:47:04 +00001996 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1997 return ExprError(Diag(TheCall->getLocStart(),
1998 diag::err_shufflevector_non_vector)
1999 << SourceRange(TheCall->getArg(0)->getLocStart(),
2000 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002001
Nate Begemana0110022010-06-08 00:16:34 +00002002 numElements = LHSType->getAs<VectorType>()->getNumElements();
2003 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002004
Nate Begemana0110022010-06-08 00:16:34 +00002005 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2006 // with mask. If so, verify that RHS is an integer vector type with the
2007 // same number of elts as lhs.
2008 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002009 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002010 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002011 return ExprError(Diag(TheCall->getLocStart(),
2012 diag::err_shufflevector_incompatible_vector)
2013 << SourceRange(TheCall->getArg(1)->getLocStart(),
2014 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002015 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002016 return ExprError(Diag(TheCall->getLocStart(),
2017 diag::err_shufflevector_incompatible_vector)
2018 << SourceRange(TheCall->getArg(0)->getLocStart(),
2019 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002020 } else if (numElements != numResElements) {
2021 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002022 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002023 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002024 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002025 }
2026
2027 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002028 if (TheCall->getArg(i)->isTypeDependent() ||
2029 TheCall->getArg(i)->isValueDependent())
2030 continue;
2031
Nate Begemana0110022010-06-08 00:16:34 +00002032 llvm::APSInt Result(32);
2033 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2034 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002035 diag::err_shufflevector_nonconstant_argument)
2036 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002037
Craig Topper50ad5b72013-08-03 17:40:38 +00002038 // Allow -1 which will be translated to undef in the IR.
2039 if (Result.isSigned() && Result.isAllOnesValue())
2040 continue;
2041
Chris Lattner7ab824e2008-08-10 02:05:13 +00002042 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002043 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002044 diag::err_shufflevector_argument_too_large)
2045 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002046 }
2047
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002048 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002049
Chris Lattner7ab824e2008-08-10 02:05:13 +00002050 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002051 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002052 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002053 }
2054
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002055 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2056 TheCall->getCallee()->getLocStart(),
2057 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002058}
Chris Lattner43be2e62007-12-19 23:59:04 +00002059
Hal Finkelc4d7c822013-09-18 03:29:45 +00002060/// SemaConvertVectorExpr - Handle __builtin_convertvector
2061ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2062 SourceLocation BuiltinLoc,
2063 SourceLocation RParenLoc) {
2064 ExprValueKind VK = VK_RValue;
2065 ExprObjectKind OK = OK_Ordinary;
2066 QualType DstTy = TInfo->getType();
2067 QualType SrcTy = E->getType();
2068
2069 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2070 return ExprError(Diag(BuiltinLoc,
2071 diag::err_convertvector_non_vector)
2072 << E->getSourceRange());
2073 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2074 return ExprError(Diag(BuiltinLoc,
2075 diag::err_convertvector_non_vector_type));
2076
2077 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2078 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2079 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2080 if (SrcElts != DstElts)
2081 return ExprError(Diag(BuiltinLoc,
2082 diag::err_convertvector_incompatible_vector)
2083 << E->getSourceRange());
2084 }
2085
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002086 return new (Context)
2087 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002088}
2089
Daniel Dunbarb7257262008-07-21 22:59:13 +00002090/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2091// This is declared to take (const void*, ...) and can take two
2092// optional constant int args.
2093bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002094 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002095
Chris Lattner3b054132008-11-19 05:08:23 +00002096 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002097 return Diag(TheCall->getLocEnd(),
2098 diag::err_typecheck_call_too_many_args_at_most)
2099 << 0 /*function call*/ << 3 << NumArgs
2100 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002101
2102 // Argument 0 is checked for us and the remaining arguments must be
2103 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002104 for (unsigned i = 1; i != NumArgs; ++i)
2105 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002106 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002107
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002108 return false;
2109}
2110
Hal Finkelf0417332014-07-17 14:25:55 +00002111/// SemaBuiltinAssume - Handle __assume (MS Extension).
2112// __assume does not evaluate its arguments, and should warn if its argument
2113// has side effects.
2114bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2115 Expr *Arg = TheCall->getArg(0);
2116 if (Arg->isInstantiationDependent()) return false;
2117
2118 if (Arg->HasSideEffects(Context))
2119 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002120 << Arg->getSourceRange()
2121 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2122
2123 return false;
2124}
2125
2126/// Handle __builtin_assume_aligned. This is declared
2127/// as (const void*, size_t, ...) and can take one optional constant int arg.
2128bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2129 unsigned NumArgs = TheCall->getNumArgs();
2130
2131 if (NumArgs > 3)
2132 return Diag(TheCall->getLocEnd(),
2133 diag::err_typecheck_call_too_many_args_at_most)
2134 << 0 /*function call*/ << 3 << NumArgs
2135 << TheCall->getSourceRange();
2136
2137 // The alignment must be a constant integer.
2138 Expr *Arg = TheCall->getArg(1);
2139
2140 // We can't check the value of a dependent argument.
2141 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2142 llvm::APSInt Result;
2143 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2144 return true;
2145
2146 if (!Result.isPowerOf2())
2147 return Diag(TheCall->getLocStart(),
2148 diag::err_alignment_not_power_of_two)
2149 << Arg->getSourceRange();
2150 }
2151
2152 if (NumArgs > 2) {
2153 ExprResult Arg(TheCall->getArg(2));
2154 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2155 Context.getSizeType(), false);
2156 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2157 if (Arg.isInvalid()) return true;
2158 TheCall->setArg(2, Arg.get());
2159 }
Hal Finkelf0417332014-07-17 14:25:55 +00002160
2161 return false;
2162}
2163
Eric Christopher8d0c6212010-04-17 02:26:23 +00002164/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2165/// TheCall is a constant expression.
2166bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2167 llvm::APSInt &Result) {
2168 Expr *Arg = TheCall->getArg(ArgNum);
2169 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2170 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2171
2172 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2173
2174 if (!Arg->isIntegerConstantExpr(Result, Context))
2175 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002176 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002177
Chris Lattnerd545ad12009-09-23 06:06:36 +00002178 return false;
2179}
2180
Richard Sandiford28940af2014-04-16 08:47:51 +00002181/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2182/// TheCall is a constant expression in the range [Low, High].
2183bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2184 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002185 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002186
2187 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002188 Expr *Arg = TheCall->getArg(ArgNum);
2189 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002190 return false;
2191
Eric Christopher8d0c6212010-04-17 02:26:23 +00002192 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002193 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002194 return true;
2195
Richard Sandiford28940af2014-04-16 08:47:51 +00002196 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002197 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002198 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002199
2200 return false;
2201}
2202
Eli Friedmanc97d0142009-05-03 06:04:26 +00002203/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002204/// This checks that val is a constant 1.
2205bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2206 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002207 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002208
Eric Christopher8d0c6212010-04-17 02:26:23 +00002209 // TODO: This is less than ideal. Overload this to take a value.
2210 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2211 return true;
2212
2213 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002214 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2215 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2216
2217 return false;
2218}
2219
Richard Smithd7293d72013-08-05 18:49:43 +00002220namespace {
2221enum StringLiteralCheckType {
2222 SLCT_NotALiteral,
2223 SLCT_UncheckedLiteral,
2224 SLCT_CheckedLiteral
2225};
2226}
2227
Richard Smith55ce3522012-06-25 20:30:08 +00002228// Determine if an expression is a string literal or constant string.
2229// If this function returns false on the arguments to a function expecting a
2230// format string, we will usually need to emit a warning.
2231// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002232static StringLiteralCheckType
2233checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2234 bool HasVAListArg, unsigned format_idx,
2235 unsigned firstDataArg, Sema::FormatStringType Type,
2236 Sema::VariadicCallType CallType, bool InFunctionCall,
2237 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002238 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002239 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002240 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002241
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002242 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002243
Richard Smithd7293d72013-08-05 18:49:43 +00002244 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002245 // Technically -Wformat-nonliteral does not warn about this case.
2246 // The behavior of printf and friends in this case is implementation
2247 // dependent. Ideally if the format string cannot be null then
2248 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002249 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002250
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002251 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002252 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002253 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002254 // The expression is a literal if both sub-expressions were, and it was
2255 // completely checked only if both sub-expressions were checked.
2256 const AbstractConditionalOperator *C =
2257 cast<AbstractConditionalOperator>(E);
2258 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002259 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002260 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002261 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002262 if (Left == SLCT_NotALiteral)
2263 return SLCT_NotALiteral;
2264 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002265 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002266 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002267 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002268 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002269 }
2270
2271 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002272 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2273 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002274 }
2275
John McCallc07a0c72011-02-17 10:25:35 +00002276 case Stmt::OpaqueValueExprClass:
2277 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2278 E = src;
2279 goto tryAgain;
2280 }
Richard Smith55ce3522012-06-25 20:30:08 +00002281 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002282
Ted Kremeneka8890832011-02-24 23:03:04 +00002283 case Stmt::PredefinedExprClass:
2284 // While __func__, etc., are technically not string literals, they
2285 // cannot contain format specifiers and thus are not a security
2286 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002287 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002288
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002289 case Stmt::DeclRefExprClass: {
2290 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002292 // As an exception, do not flag errors for variables binding to
2293 // const string literals.
2294 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2295 bool isConstant = false;
2296 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002297
Richard Smithd7293d72013-08-05 18:49:43 +00002298 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2299 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002300 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002301 isConstant = T.isConstant(S.Context) &&
2302 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002303 } else if (T->isObjCObjectPointerType()) {
2304 // In ObjC, there is usually no "const ObjectPointer" type,
2305 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002306 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002309 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002310 if (const Expr *Init = VD->getAnyInitializer()) {
2311 // Look through initializers like const char c[] = { "foo" }
2312 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2313 if (InitList->isStringLiteralInit())
2314 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2315 }
Richard Smithd7293d72013-08-05 18:49:43 +00002316 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002317 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002318 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002319 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002320 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002321 }
Mike Stump11289f42009-09-09 15:08:12 +00002322
Anders Carlssonb012ca92009-06-28 19:55:58 +00002323 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2324 // special check to see if the format string is a function parameter
2325 // of the function calling the printf function. If the function
2326 // has an attribute indicating it is a printf-like function, then we
2327 // should suppress warnings concerning non-literals being used in a call
2328 // to a vprintf function. For example:
2329 //
2330 // void
2331 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2332 // va_list ap;
2333 // va_start(ap, fmt);
2334 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2335 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002336 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002337 if (HasVAListArg) {
2338 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2339 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2340 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002341 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002342 // adjust for implicit parameter
2343 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2344 if (MD->isInstance())
2345 ++PVIndex;
2346 // We also check if the formats are compatible.
2347 // We can't pass a 'scanf' string to a 'printf' function.
2348 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002349 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002350 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002351 }
2352 }
2353 }
2354 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Richard Smith55ce3522012-06-25 20:30:08 +00002357 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002358 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002359
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002360 case Stmt::CallExprClass:
2361 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002362 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002363 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2364 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2365 unsigned ArgIndex = FA->getFormatIdx();
2366 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2367 if (MD->isInstance())
2368 --ArgIndex;
2369 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002370
Richard Smithd7293d72013-08-05 18:49:43 +00002371 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002372 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002373 Type, CallType, InFunctionCall,
2374 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002375 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2376 unsigned BuiltinID = FD->getBuiltinID();
2377 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2378 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2379 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002380 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002381 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002382 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002383 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002384 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002385 }
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Richard Smith55ce3522012-06-25 20:30:08 +00002388 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002389 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002390 case Stmt::ObjCStringLiteralClass:
2391 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002392 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002393
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002394 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002395 StrE = ObjCFExpr->getString();
2396 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002397 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002398
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002399 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002400 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2401 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002402 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Richard Smith55ce3522012-06-25 20:30:08 +00002405 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002408 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002409 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002410 }
2411}
2412
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002413Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002414 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002415 .Case("scanf", FST_Scanf)
2416 .Cases("printf", "printf0", FST_Printf)
2417 .Cases("NSString", "CFString", FST_NSString)
2418 .Case("strftime", FST_Strftime)
2419 .Case("strfmon", FST_Strfmon)
2420 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2421 .Default(FST_Unknown);
2422}
2423
Jordan Rose3e0ec582012-07-19 18:10:23 +00002424/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002425/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002426/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002427bool Sema::CheckFormatArguments(const FormatAttr *Format,
2428 ArrayRef<const Expr *> Args,
2429 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002430 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002431 SourceLocation Loc, SourceRange Range,
2432 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002433 FormatStringInfo FSI;
2434 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002435 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002436 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002437 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002438 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002439}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002440
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002441bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002442 bool HasVAListArg, unsigned format_idx,
2443 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002444 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002445 SourceLocation Loc, SourceRange Range,
2446 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002447 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002448 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002449 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002450 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002453 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002455 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002456 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002457 // Dynamically generated format strings are difficult to
2458 // automatically vet at compile time. Requiring that format strings
2459 // are string literals: (1) permits the checking of format strings by
2460 // the compiler and thereby (2) can practically remove the source of
2461 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002462
Mike Stump11289f42009-09-09 15:08:12 +00002463 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002464 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002465 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002466 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002467 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002468 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2469 format_idx, firstDataArg, Type, CallType,
2470 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002471 if (CT != SLCT_NotALiteral)
2472 // Literal format string found, check done!
2473 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002474
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002475 // Strftime is particular as it always uses a single 'time' argument,
2476 // so it is safe to pass a non-literal string.
2477 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002478 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002479
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002480 // Do not emit diag when the string param is a macro expansion and the
2481 // format is either NSString or CFString. This is a hack to prevent
2482 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2483 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002484 if (Type == FST_NSString &&
2485 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002486 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002487
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002488 // If there are no arguments specified, warn with -Wformat-security, otherwise
2489 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002490 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002491 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002492 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002493 << OrigFormatExpr->getSourceRange();
2494 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002495 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002496 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002497 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002498 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002499}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002500
Ted Kremenekab278de2010-01-28 23:39:18 +00002501namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002502class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2503protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002504 Sema &S;
2505 const StringLiteral *FExpr;
2506 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002507 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002508 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002509 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002510 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002511 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002512 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002513 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002514 bool usesPositionalArgs;
2515 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002516 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002517 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002518 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002519public:
Ted Kremenek02087932010-07-16 02:11:22 +00002520 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002521 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002522 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002523 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002524 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002525 Sema::VariadicCallType callType,
2526 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002527 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002528 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2529 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002530 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002531 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002532 inFunctionCall(inFunctionCall), CallType(callType),
2533 CheckedVarArgs(CheckedVarArgs) {
2534 CoveredArgs.resize(numDataArgs);
2535 CoveredArgs.reset();
2536 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002537
Ted Kremenek019d2242010-01-29 01:50:07 +00002538 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002539
Ted Kremenek02087932010-07-16 02:11:22 +00002540 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002541 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002542
Jordan Rose92303592012-09-08 04:00:03 +00002543 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002544 const analyze_format_string::FormatSpecifier &FS,
2545 const analyze_format_string::ConversionSpecifier &CS,
2546 const char *startSpecifier, unsigned specifierLen,
2547 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002548
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002549 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002550 const analyze_format_string::FormatSpecifier &FS,
2551 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002552
2553 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002554 const analyze_format_string::ConversionSpecifier &CS,
2555 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002556
Craig Toppere14c0f82014-03-12 04:55:44 +00002557 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002558
Craig Toppere14c0f82014-03-12 04:55:44 +00002559 void HandleInvalidPosition(const char *startSpecifier,
2560 unsigned specifierLen,
2561 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002562
Craig Toppere14c0f82014-03-12 04:55:44 +00002563 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002564
Craig Toppere14c0f82014-03-12 04:55:44 +00002565 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002566
Richard Trieu03cf7b72011-10-28 00:41:25 +00002567 template <typename Range>
2568 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2569 const Expr *ArgumentExpr,
2570 PartialDiagnostic PDiag,
2571 SourceLocation StringLoc,
2572 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002573 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002574
Ted Kremenek02087932010-07-16 02:11:22 +00002575protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002576 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2577 const char *startSpec,
2578 unsigned specifierLen,
2579 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002580
2581 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2582 const char *startSpec,
2583 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002584
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002585 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002586 CharSourceRange getSpecifierRange(const char *startSpecifier,
2587 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002588 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002589
Ted Kremenek5739de72010-01-29 01:06:55 +00002590 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002591
2592 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2593 const analyze_format_string::ConversionSpecifier &CS,
2594 const char *startSpecifier, unsigned specifierLen,
2595 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002596
2597 template <typename Range>
2598 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2599 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002600 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002601};
2602}
2603
Ted Kremenek02087932010-07-16 02:11:22 +00002604SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002605 return OrigFormatExpr->getSourceRange();
2606}
2607
Ted Kremenek02087932010-07-16 02:11:22 +00002608CharSourceRange CheckFormatHandler::
2609getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002610 SourceLocation Start = getLocationOfByte(startSpecifier);
2611 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2612
2613 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002614 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002615
2616 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002617}
2618
Ted Kremenek02087932010-07-16 02:11:22 +00002619SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002620 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002621}
2622
Ted Kremenek02087932010-07-16 02:11:22 +00002623void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2624 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002625 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2626 getLocationOfByte(startSpecifier),
2627 /*IsStringLocation*/true,
2628 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002629}
2630
Jordan Rose92303592012-09-08 04:00:03 +00002631void CheckFormatHandler::HandleInvalidLengthModifier(
2632 const analyze_format_string::FormatSpecifier &FS,
2633 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002634 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002635 using namespace analyze_format_string;
2636
2637 const LengthModifier &LM = FS.getLengthModifier();
2638 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2639
2640 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002641 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002642 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002643 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002644 getLocationOfByte(LM.getStart()),
2645 /*IsStringLocation*/true,
2646 getSpecifierRange(startSpecifier, specifierLen));
2647
2648 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2649 << FixedLM->toString()
2650 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2651
2652 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002653 FixItHint Hint;
2654 if (DiagID == diag::warn_format_nonsensical_length)
2655 Hint = FixItHint::CreateRemoval(LMRange);
2656
2657 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002658 getLocationOfByte(LM.getStart()),
2659 /*IsStringLocation*/true,
2660 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002661 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002662 }
2663}
2664
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002665void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002666 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002667 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002668 using namespace analyze_format_string;
2669
2670 const LengthModifier &LM = FS.getLengthModifier();
2671 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2672
2673 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002674 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002675 if (FixedLM) {
2676 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2677 << LM.toString() << 0,
2678 getLocationOfByte(LM.getStart()),
2679 /*IsStringLocation*/true,
2680 getSpecifierRange(startSpecifier, specifierLen));
2681
2682 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2683 << FixedLM->toString()
2684 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2685
2686 } else {
2687 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2688 << LM.toString() << 0,
2689 getLocationOfByte(LM.getStart()),
2690 /*IsStringLocation*/true,
2691 getSpecifierRange(startSpecifier, specifierLen));
2692 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002693}
2694
2695void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2696 const analyze_format_string::ConversionSpecifier &CS,
2697 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002698 using namespace analyze_format_string;
2699
2700 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002701 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002702 if (FixedCS) {
2703 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2704 << CS.toString() << /*conversion specifier*/1,
2705 getLocationOfByte(CS.getStart()),
2706 /*IsStringLocation*/true,
2707 getSpecifierRange(startSpecifier, specifierLen));
2708
2709 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2710 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2711 << FixedCS->toString()
2712 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2713 } else {
2714 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2715 << CS.toString() << /*conversion specifier*/1,
2716 getLocationOfByte(CS.getStart()),
2717 /*IsStringLocation*/true,
2718 getSpecifierRange(startSpecifier, specifierLen));
2719 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002720}
2721
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002722void CheckFormatHandler::HandlePosition(const char *startPos,
2723 unsigned posLen) {
2724 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2725 getLocationOfByte(startPos),
2726 /*IsStringLocation*/true,
2727 getSpecifierRange(startPos, posLen));
2728}
2729
Ted Kremenekd1668192010-02-27 01:41:03 +00002730void
Ted Kremenek02087932010-07-16 02:11:22 +00002731CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2732 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002733 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2734 << (unsigned) p,
2735 getLocationOfByte(startPos), /*IsStringLocation*/true,
2736 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002737}
2738
Ted Kremenek02087932010-07-16 02:11:22 +00002739void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002740 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002741 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2742 getLocationOfByte(startPos),
2743 /*IsStringLocation*/true,
2744 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002745}
2746
Ted Kremenek02087932010-07-16 02:11:22 +00002747void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002748 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002749 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002750 EmitFormatDiagnostic(
2751 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2752 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2753 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002754 }
Ted Kremenek02087932010-07-16 02:11:22 +00002755}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002756
Jordan Rose58bbe422012-07-19 18:10:08 +00002757// Note that this may return NULL if there was an error parsing or building
2758// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002759const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002760 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002761}
2762
2763void CheckFormatHandler::DoneProcessing() {
2764 // Does the number of data arguments exceed the number of
2765 // format conversions in the format string?
2766 if (!HasVAListArg) {
2767 // Find any arguments that weren't covered.
2768 CoveredArgs.flip();
2769 signed notCoveredArg = CoveredArgs.find_first();
2770 if (notCoveredArg >= 0) {
2771 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002772 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2773 SourceLocation Loc = E->getLocStart();
2774 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2776 Loc, /*IsStringLocation*/false,
2777 getFormatStringRange());
2778 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002779 }
Ted Kremenek02087932010-07-16 02:11:22 +00002780 }
2781 }
2782}
2783
Ted Kremenekce815422010-07-19 21:25:57 +00002784bool
2785CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2786 SourceLocation Loc,
2787 const char *startSpec,
2788 unsigned specifierLen,
2789 const char *csStart,
2790 unsigned csLen) {
2791
2792 bool keepGoing = true;
2793 if (argIndex < NumDataArgs) {
2794 // Consider the argument coverered, even though the specifier doesn't
2795 // make sense.
2796 CoveredArgs.set(argIndex);
2797 }
2798 else {
2799 // If argIndex exceeds the number of data arguments we
2800 // don't issue a warning because that is just a cascade of warnings (and
2801 // they may have intended '%%' anyway). We don't want to continue processing
2802 // the format string after this point, however, as we will like just get
2803 // gibberish when trying to match arguments.
2804 keepGoing = false;
2805 }
2806
Richard Trieu03cf7b72011-10-28 00:41:25 +00002807 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2808 << StringRef(csStart, csLen),
2809 Loc, /*IsStringLocation*/true,
2810 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002811
2812 return keepGoing;
2813}
2814
Richard Trieu03cf7b72011-10-28 00:41:25 +00002815void
2816CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2817 const char *startSpec,
2818 unsigned specifierLen) {
2819 EmitFormatDiagnostic(
2820 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2821 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2822}
2823
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002824bool
2825CheckFormatHandler::CheckNumArgs(
2826 const analyze_format_string::FormatSpecifier &FS,
2827 const analyze_format_string::ConversionSpecifier &CS,
2828 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2829
2830 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002831 PartialDiagnostic PDiag = FS.usesPositionalArg()
2832 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2833 << (argIndex+1) << NumDataArgs)
2834 : S.PDiag(diag::warn_printf_insufficient_data_args);
2835 EmitFormatDiagnostic(
2836 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2837 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002838 return false;
2839 }
2840 return true;
2841}
2842
Richard Trieu03cf7b72011-10-28 00:41:25 +00002843template<typename Range>
2844void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2845 SourceLocation Loc,
2846 bool IsStringLocation,
2847 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002848 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002849 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002850 Loc, IsStringLocation, StringRange, FixIt);
2851}
2852
2853/// \brief If the format string is not within the funcion call, emit a note
2854/// so that the function call and string are in diagnostic messages.
2855///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002856/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002857/// call and only one diagnostic message will be produced. Otherwise, an
2858/// extra note will be emitted pointing to location of the format string.
2859///
2860/// \param ArgumentExpr the expression that is passed as the format string
2861/// argument in the function call. Used for getting locations when two
2862/// diagnostics are emitted.
2863///
2864/// \param PDiag the callee should already have provided any strings for the
2865/// diagnostic message. This function only adds locations and fixits
2866/// to diagnostics.
2867///
2868/// \param Loc primary location for diagnostic. If two diagnostics are
2869/// required, one will be at Loc and a new SourceLocation will be created for
2870/// the other one.
2871///
2872/// \param IsStringLocation if true, Loc points to the format string should be
2873/// used for the note. Otherwise, Loc points to the argument list and will
2874/// be used with PDiag.
2875///
2876/// \param StringRange some or all of the string to highlight. This is
2877/// templated so it can accept either a CharSourceRange or a SourceRange.
2878///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002879/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002880template<typename Range>
2881void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2882 const Expr *ArgumentExpr,
2883 PartialDiagnostic PDiag,
2884 SourceLocation Loc,
2885 bool IsStringLocation,
2886 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002887 ArrayRef<FixItHint> FixIt) {
2888 if (InFunctionCall) {
2889 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2890 D << StringRange;
2891 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2892 I != E; ++I) {
2893 D << *I;
2894 }
2895 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002896 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2897 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002898
2899 const Sema::SemaDiagnosticBuilder &Note =
2900 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2901 diag::note_format_string_defined);
2902
2903 Note << StringRange;
2904 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2905 I != E; ++I) {
2906 Note << *I;
2907 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002908 }
2909}
2910
Ted Kremenek02087932010-07-16 02:11:22 +00002911//===--- CHECK: Printf format string checking ------------------------------===//
2912
2913namespace {
2914class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002915 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002916public:
2917 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2918 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002919 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002920 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002921 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002922 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002923 Sema::VariadicCallType CallType,
2924 llvm::SmallBitVector &CheckedVarArgs)
2925 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2926 numDataArgs, beg, hasVAListArg, Args,
2927 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2928 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002929 {}
2930
Craig Toppere14c0f82014-03-12 04:55:44 +00002931
Ted Kremenek02087932010-07-16 02:11:22 +00002932 bool HandleInvalidPrintfConversionSpecifier(
2933 const analyze_printf::PrintfSpecifier &FS,
2934 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002935 unsigned specifierLen) override;
2936
Ted Kremenek02087932010-07-16 02:11:22 +00002937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2938 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002939 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002940 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2941 const char *StartSpecifier,
2942 unsigned SpecifierLen,
2943 const Expr *E);
2944
Ted Kremenek02087932010-07-16 02:11:22 +00002945 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2946 const char *startSpecifier, unsigned specifierLen);
2947 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2948 const analyze_printf::OptionalAmount &Amt,
2949 unsigned type,
2950 const char *startSpecifier, unsigned specifierLen);
2951 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2952 const analyze_printf::OptionalFlag &flag,
2953 const char *startSpecifier, unsigned specifierLen);
2954 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2955 const analyze_printf::OptionalFlag &ignoredFlag,
2956 const analyze_printf::OptionalFlag &flag,
2957 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002958 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002959 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002960
Ted Kremenek02087932010-07-16 02:11:22 +00002961};
2962}
2963
2964bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2965 const analyze_printf::PrintfSpecifier &FS,
2966 const char *startSpecifier,
2967 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002968 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002969 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002970
Ted Kremenekce815422010-07-19 21:25:57 +00002971 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2972 getLocationOfByte(CS.getStart()),
2973 startSpecifier, specifierLen,
2974 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002975}
2976
Ted Kremenek02087932010-07-16 02:11:22 +00002977bool CheckPrintfHandler::HandleAmount(
2978 const analyze_format_string::OptionalAmount &Amt,
2979 unsigned k, const char *startSpecifier,
2980 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002981
2982 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002983 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002984 unsigned argIndex = Amt.getArgIndex();
2985 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002986 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2987 << k,
2988 getLocationOfByte(Amt.getStart()),
2989 /*IsStringLocation*/true,
2990 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002991 // Don't do any more checking. We will just emit
2992 // spurious errors.
2993 return false;
2994 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002995
Ted Kremenek5739de72010-01-29 01:06:55 +00002996 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002997 // Although not in conformance with C99, we also allow the argument to be
2998 // an 'unsigned int' as that is a reasonably safe case. GCC also
2999 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003000 CoveredArgs.set(argIndex);
3001 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003002 if (!Arg)
3003 return false;
3004
Ted Kremenek5739de72010-01-29 01:06:55 +00003005 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003006
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003007 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3008 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003009
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003010 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003011 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003012 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003013 << T << Arg->getSourceRange(),
3014 getLocationOfByte(Amt.getStart()),
3015 /*IsStringLocation*/true,
3016 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003017 // Don't do any more checking. We will just emit
3018 // spurious errors.
3019 return false;
3020 }
3021 }
3022 }
3023 return true;
3024}
Ted Kremenek5739de72010-01-29 01:06:55 +00003025
Tom Careb49ec692010-06-17 19:00:27 +00003026void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003027 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003028 const analyze_printf::OptionalAmount &Amt,
3029 unsigned type,
3030 const char *startSpecifier,
3031 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003032 const analyze_printf::PrintfConversionSpecifier &CS =
3033 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003034
Richard Trieu03cf7b72011-10-28 00:41:25 +00003035 FixItHint fixit =
3036 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3037 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3038 Amt.getConstantLength()))
3039 : FixItHint();
3040
3041 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3042 << type << CS.toString(),
3043 getLocationOfByte(Amt.getStart()),
3044 /*IsStringLocation*/true,
3045 getSpecifierRange(startSpecifier, specifierLen),
3046 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003047}
3048
Ted Kremenek02087932010-07-16 02:11:22 +00003049void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003050 const analyze_printf::OptionalFlag &flag,
3051 const char *startSpecifier,
3052 unsigned specifierLen) {
3053 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003054 const analyze_printf::PrintfConversionSpecifier &CS =
3055 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003056 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3057 << flag.toString() << CS.toString(),
3058 getLocationOfByte(flag.getPosition()),
3059 /*IsStringLocation*/true,
3060 getSpecifierRange(startSpecifier, specifierLen),
3061 FixItHint::CreateRemoval(
3062 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003063}
3064
3065void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003066 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003067 const analyze_printf::OptionalFlag &ignoredFlag,
3068 const analyze_printf::OptionalFlag &flag,
3069 const char *startSpecifier,
3070 unsigned specifierLen) {
3071 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003072 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3073 << ignoredFlag.toString() << flag.toString(),
3074 getLocationOfByte(ignoredFlag.getPosition()),
3075 /*IsStringLocation*/true,
3076 getSpecifierRange(startSpecifier, specifierLen),
3077 FixItHint::CreateRemoval(
3078 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003079}
3080
Richard Smith55ce3522012-06-25 20:30:08 +00003081// Determines if the specified is a C++ class or struct containing
3082// a member with the specified name and kind (e.g. a CXXMethodDecl named
3083// "c_str()").
3084template<typename MemberKind>
3085static llvm::SmallPtrSet<MemberKind*, 1>
3086CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3087 const RecordType *RT = Ty->getAs<RecordType>();
3088 llvm::SmallPtrSet<MemberKind*, 1> Results;
3089
3090 if (!RT)
3091 return Results;
3092 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003093 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003094 return Results;
3095
Alp Tokerb6cc5922014-05-03 03:45:55 +00003096 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003097 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003098 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003099
3100 // We just need to include all members of the right kind turned up by the
3101 // filter, at this point.
3102 if (S.LookupQualifiedName(R, RT->getDecl()))
3103 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3104 NamedDecl *decl = (*I)->getUnderlyingDecl();
3105 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3106 Results.insert(FK);
3107 }
3108 return Results;
3109}
3110
Richard Smith2868a732014-02-28 01:36:39 +00003111/// Check if we could call '.c_str()' on an object.
3112///
3113/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3114/// allow the call, or if it would be ambiguous).
3115bool Sema::hasCStrMethod(const Expr *E) {
3116 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3117 MethodSet Results =
3118 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3119 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3120 MI != ME; ++MI)
3121 if ((*MI)->getMinRequiredArguments() == 0)
3122 return true;
3123 return false;
3124}
3125
Richard Smith55ce3522012-06-25 20:30:08 +00003126// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003127// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003128// Returns true when a c_str() conversion method is found.
3129bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003130 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003131 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3132
3133 MethodSet Results =
3134 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3135
3136 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3137 MI != ME; ++MI) {
3138 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003139 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003140 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003141 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003142 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003143 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3144 << "c_str()"
3145 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3146 return true;
3147 }
3148 }
3149
3150 return false;
3151}
3152
Ted Kremenekab278de2010-01-28 23:39:18 +00003153bool
Ted Kremenek02087932010-07-16 02:11:22 +00003154CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003155 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003156 const char *startSpecifier,
3157 unsigned specifierLen) {
3158
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003159 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003160 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003161 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003162
Ted Kremenek6cd69422010-07-19 22:01:06 +00003163 if (FS.consumesDataArgument()) {
3164 if (atFirstArg) {
3165 atFirstArg = false;
3166 usesPositionalArgs = FS.usesPositionalArg();
3167 }
3168 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003169 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3170 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003171 return false;
3172 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003173 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003174
Ted Kremenekd1668192010-02-27 01:41:03 +00003175 // First check if the field width, precision, and conversion specifier
3176 // have matching data arguments.
3177 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3178 startSpecifier, specifierLen)) {
3179 return false;
3180 }
3181
3182 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3183 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003184 return false;
3185 }
3186
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003187 if (!CS.consumesDataArgument()) {
3188 // FIXME: Technically specifying a precision or field width here
3189 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003190 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003191 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003192
Ted Kremenek4a49d982010-02-26 19:18:41 +00003193 // Consume the argument.
3194 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003195 if (argIndex < NumDataArgs) {
3196 // The check to see if the argIndex is valid will come later.
3197 // We set the bit here because we may exit early from this
3198 // function if we encounter some other error.
3199 CoveredArgs.set(argIndex);
3200 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003201
3202 // Check for using an Objective-C specific conversion specifier
3203 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003204 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003205 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3206 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003207 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003208
Tom Careb49ec692010-06-17 19:00:27 +00003209 // Check for invalid use of field width
3210 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003211 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003212 startSpecifier, specifierLen);
3213 }
3214
3215 // Check for invalid use of precision
3216 if (!FS.hasValidPrecision()) {
3217 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3218 startSpecifier, specifierLen);
3219 }
3220
3221 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003222 if (!FS.hasValidThousandsGroupingPrefix())
3223 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003224 if (!FS.hasValidLeadingZeros())
3225 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3226 if (!FS.hasValidPlusPrefix())
3227 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003228 if (!FS.hasValidSpacePrefix())
3229 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003230 if (!FS.hasValidAlternativeForm())
3231 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3232 if (!FS.hasValidLeftJustified())
3233 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3234
3235 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003236 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3237 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3238 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003239 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3240 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3241 startSpecifier, specifierLen);
3242
3243 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003244 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003245 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3246 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003247 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003248 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003249 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003250 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3251 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003252
Jordan Rose92303592012-09-08 04:00:03 +00003253 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3254 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3255
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003256 // The remaining checks depend on the data arguments.
3257 if (HasVAListArg)
3258 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003259
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003260 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003261 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003262
Jordan Rose58bbe422012-07-19 18:10:08 +00003263 const Expr *Arg = getDataArg(argIndex);
3264 if (!Arg)
3265 return true;
3266
3267 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003268}
3269
Jordan Roseaee34382012-09-05 22:56:26 +00003270static bool requiresParensToAddCast(const Expr *E) {
3271 // FIXME: We should have a general way to reason about operator
3272 // precedence and whether parens are actually needed here.
3273 // Take care of a few common cases where they aren't.
3274 const Expr *Inside = E->IgnoreImpCasts();
3275 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3276 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3277
3278 switch (Inside->getStmtClass()) {
3279 case Stmt::ArraySubscriptExprClass:
3280 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003281 case Stmt::CharacterLiteralClass:
3282 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003283 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003284 case Stmt::FloatingLiteralClass:
3285 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003286 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003287 case Stmt::ObjCArrayLiteralClass:
3288 case Stmt::ObjCBoolLiteralExprClass:
3289 case Stmt::ObjCBoxedExprClass:
3290 case Stmt::ObjCDictionaryLiteralClass:
3291 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003292 case Stmt::ObjCIvarRefExprClass:
3293 case Stmt::ObjCMessageExprClass:
3294 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003295 case Stmt::ObjCStringLiteralClass:
3296 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003297 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003298 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003299 case Stmt::UnaryOperatorClass:
3300 return false;
3301 default:
3302 return true;
3303 }
3304}
3305
Richard Smith55ce3522012-06-25 20:30:08 +00003306bool
3307CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3308 const char *StartSpecifier,
3309 unsigned SpecifierLen,
3310 const Expr *E) {
3311 using namespace analyze_format_string;
3312 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003313 // Now type check the data expression that matches the
3314 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003315 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3316 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003317 if (!AT.isValid())
3318 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003319
Jordan Rose598ec092012-12-05 18:44:40 +00003320 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003321 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3322 ExprTy = TET->getUnderlyingExpr()->getType();
3323 }
3324
Jordan Rose598ec092012-12-05 18:44:40 +00003325 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003326 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003327
Jordan Rose22b74712012-09-05 22:56:19 +00003328 // Look through argument promotions for our error message's reported type.
3329 // This includes the integral and floating promotions, but excludes array
3330 // and function pointer decay; seeing that an argument intended to be a
3331 // string has type 'char [6]' is probably more confusing than 'char *'.
3332 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3333 if (ICE->getCastKind() == CK_IntegralCast ||
3334 ICE->getCastKind() == CK_FloatingCast) {
3335 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003336 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003337
3338 // Check if we didn't match because of an implicit cast from a 'char'
3339 // or 'short' to an 'int'. This is done because printf is a varargs
3340 // function.
3341 if (ICE->getType() == S.Context.IntTy ||
3342 ICE->getType() == S.Context.UnsignedIntTy) {
3343 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003344 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003345 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003346 }
Jordan Rose98709982012-06-04 22:48:57 +00003347 }
Jordan Rose598ec092012-12-05 18:44:40 +00003348 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3349 // Special case for 'a', which has type 'int' in C.
3350 // Note, however, that we do /not/ want to treat multibyte constants like
3351 // 'MooV' as characters! This form is deprecated but still exists.
3352 if (ExprTy == S.Context.IntTy)
3353 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3354 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003355 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003356
Jordan Rosebc53ed12014-05-31 04:12:14 +00003357 // Look through enums to their underlying type.
3358 bool IsEnum = false;
3359 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3360 ExprTy = EnumTy->getDecl()->getIntegerType();
3361 IsEnum = true;
3362 }
3363
Jordan Rose0e5badd2012-12-05 18:44:49 +00003364 // %C in an Objective-C context prints a unichar, not a wchar_t.
3365 // If the argument is an integer of some kind, believe the %C and suggest
3366 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003367 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003368 if (ObjCContext &&
3369 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3370 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3371 !ExprTy->isCharType()) {
3372 // 'unichar' is defined as a typedef of unsigned short, but we should
3373 // prefer using the typedef if it is visible.
3374 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003375
3376 // While we are here, check if the value is an IntegerLiteral that happens
3377 // to be within the valid range.
3378 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3379 const llvm::APInt &V = IL->getValue();
3380 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3381 return true;
3382 }
3383
Jordan Rose0e5badd2012-12-05 18:44:49 +00003384 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3385 Sema::LookupOrdinaryName);
3386 if (S.LookupName(Result, S.getCurScope())) {
3387 NamedDecl *ND = Result.getFoundDecl();
3388 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3389 if (TD->getUnderlyingType() == IntendedTy)
3390 IntendedTy = S.Context.getTypedefType(TD);
3391 }
3392 }
3393 }
3394
3395 // Special-case some of Darwin's platform-independence types by suggesting
3396 // casts to primitive types that are known to be large enough.
3397 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003398 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003399 // Use a 'while' to peel off layers of typedefs.
3400 QualType TyTy = IntendedTy;
3401 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003402 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003403 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003404 .Case("NSInteger", S.Context.LongTy)
3405 .Case("NSUInteger", S.Context.UnsignedLongTy)
3406 .Case("SInt32", S.Context.IntTy)
3407 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003408 .Default(QualType());
3409
3410 if (!CastTy.isNull()) {
3411 ShouldNotPrintDirectly = true;
3412 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003413 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003414 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003415 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003416 }
3417 }
3418
Jordan Rose22b74712012-09-05 22:56:19 +00003419 // We may be able to offer a FixItHint if it is a supported type.
3420 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003421 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003422 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003423
Jordan Rose22b74712012-09-05 22:56:19 +00003424 if (success) {
3425 // Get the fix string from the fixed format specifier
3426 SmallString<16> buf;
3427 llvm::raw_svector_ostream os(buf);
3428 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003429
Jordan Roseaee34382012-09-05 22:56:26 +00003430 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3431
Jordan Rose0e5badd2012-12-05 18:44:49 +00003432 if (IntendedTy == ExprTy) {
3433 // In this case, the specifier is wrong and should be changed to match
3434 // the argument.
3435 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003436 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3437 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003438 << E->getSourceRange(),
3439 E->getLocStart(),
3440 /*IsStringLocation*/false,
3441 SpecRange,
3442 FixItHint::CreateReplacement(SpecRange, os.str()));
3443
3444 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003445 // The canonical type for formatting this value is different from the
3446 // actual type of the expression. (This occurs, for example, with Darwin's
3447 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3448 // should be printed as 'long' for 64-bit compatibility.)
3449 // Rather than emitting a normal format/argument mismatch, we want to
3450 // add a cast to the recommended type (and correct the format string
3451 // if necessary).
3452 SmallString<16> CastBuf;
3453 llvm::raw_svector_ostream CastFix(CastBuf);
3454 CastFix << "(";
3455 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3456 CastFix << ")";
3457
3458 SmallVector<FixItHint,4> Hints;
3459 if (!AT.matchesType(S.Context, IntendedTy))
3460 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3461
3462 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3463 // If there's already a cast present, just replace it.
3464 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3465 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3466
3467 } else if (!requiresParensToAddCast(E)) {
3468 // If the expression has high enough precedence,
3469 // just write the C-style cast.
3470 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3471 CastFix.str()));
3472 } else {
3473 // Otherwise, add parens around the expression as well as the cast.
3474 CastFix << "(";
3475 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3476 CastFix.str()));
3477
Alp Tokerb6cc5922014-05-03 03:45:55 +00003478 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003479 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3480 }
3481
Jordan Rose0e5badd2012-12-05 18:44:49 +00003482 if (ShouldNotPrintDirectly) {
3483 // The expression has a type that should not be printed directly.
3484 // We extract the name from the typedef because we don't want to show
3485 // the underlying type in the diagnostic.
3486 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003487
Jordan Rose0e5badd2012-12-05 18:44:49 +00003488 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003489 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003490 << E->getSourceRange(),
3491 E->getLocStart(), /*IsStringLocation=*/false,
3492 SpecRange, Hints);
3493 } else {
3494 // In this case, the expression could be printed using a different
3495 // specifier, but we've decided that the specifier is probably correct
3496 // and we should cast instead. Just use the normal warning message.
3497 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003498 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3499 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003500 << E->getSourceRange(),
3501 E->getLocStart(), /*IsStringLocation*/false,
3502 SpecRange, Hints);
3503 }
Jordan Roseaee34382012-09-05 22:56:26 +00003504 }
Jordan Rose22b74712012-09-05 22:56:19 +00003505 } else {
3506 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3507 SpecifierLen);
3508 // Since the warning for passing non-POD types to variadic functions
3509 // was deferred until now, we emit a warning for non-POD
3510 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003511 switch (S.isValidVarArgType(ExprTy)) {
3512 case Sema::VAK_Valid:
3513 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003514 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003515 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3516 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003517 << CSR
3518 << E->getSourceRange(),
3519 E->getLocStart(), /*IsStringLocation*/false, CSR);
3520 break;
3521
3522 case Sema::VAK_Undefined:
3523 EmitFormatDiagnostic(
3524 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003525 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003526 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003527 << CallType
3528 << AT.getRepresentativeTypeName(S.Context)
3529 << CSR
3530 << E->getSourceRange(),
3531 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003532 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003533 break;
3534
3535 case Sema::VAK_Invalid:
3536 if (ExprTy->isObjCObjectType())
3537 EmitFormatDiagnostic(
3538 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3539 << S.getLangOpts().CPlusPlus11
3540 << ExprTy
3541 << CallType
3542 << AT.getRepresentativeTypeName(S.Context)
3543 << CSR
3544 << E->getSourceRange(),
3545 E->getLocStart(), /*IsStringLocation*/false, CSR);
3546 else
3547 // FIXME: If this is an initializer list, suggest removing the braces
3548 // or inserting a cast to the target type.
3549 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3550 << isa<InitListExpr>(E) << ExprTy << CallType
3551 << AT.getRepresentativeTypeName(S.Context)
3552 << E->getSourceRange();
3553 break;
3554 }
3555
3556 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3557 "format string specifier index out of range");
3558 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003559 }
3560
Ted Kremenekab278de2010-01-28 23:39:18 +00003561 return true;
3562}
3563
Ted Kremenek02087932010-07-16 02:11:22 +00003564//===--- CHECK: Scanf format string checking ------------------------------===//
3565
3566namespace {
3567class CheckScanfHandler : public CheckFormatHandler {
3568public:
3569 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3570 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003571 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003572 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003573 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003574 Sema::VariadicCallType CallType,
3575 llvm::SmallBitVector &CheckedVarArgs)
3576 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3577 numDataArgs, beg, hasVAListArg,
3578 Args, formatIdx, inFunctionCall, CallType,
3579 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003580 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003581
3582 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3583 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003584 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003585
3586 bool HandleInvalidScanfConversionSpecifier(
3587 const analyze_scanf::ScanfSpecifier &FS,
3588 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003589 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003590
Craig Toppere14c0f82014-03-12 04:55:44 +00003591 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003592};
Ted Kremenek019d2242010-01-29 01:50:07 +00003593}
Ted Kremenekab278de2010-01-28 23:39:18 +00003594
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003595void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3596 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003597 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3598 getLocationOfByte(end), /*IsStringLocation*/true,
3599 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003600}
3601
Ted Kremenekce815422010-07-19 21:25:57 +00003602bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3603 const analyze_scanf::ScanfSpecifier &FS,
3604 const char *startSpecifier,
3605 unsigned specifierLen) {
3606
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003607 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003608 FS.getConversionSpecifier();
3609
3610 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3611 getLocationOfByte(CS.getStart()),
3612 startSpecifier, specifierLen,
3613 CS.getStart(), CS.getLength());
3614}
3615
Ted Kremenek02087932010-07-16 02:11:22 +00003616bool CheckScanfHandler::HandleScanfSpecifier(
3617 const analyze_scanf::ScanfSpecifier &FS,
3618 const char *startSpecifier,
3619 unsigned specifierLen) {
3620
3621 using namespace analyze_scanf;
3622 using namespace analyze_format_string;
3623
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003624 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003625
Ted Kremenek6cd69422010-07-19 22:01:06 +00003626 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3627 // be used to decide if we are using positional arguments consistently.
3628 if (FS.consumesDataArgument()) {
3629 if (atFirstArg) {
3630 atFirstArg = false;
3631 usesPositionalArgs = FS.usesPositionalArg();
3632 }
3633 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003634 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3635 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003636 return false;
3637 }
Ted Kremenek02087932010-07-16 02:11:22 +00003638 }
3639
3640 // Check if the field with is non-zero.
3641 const OptionalAmount &Amt = FS.getFieldWidth();
3642 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3643 if (Amt.getConstantAmount() == 0) {
3644 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3645 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3647 getLocationOfByte(Amt.getStart()),
3648 /*IsStringLocation*/true, R,
3649 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003650 }
3651 }
3652
3653 if (!FS.consumesDataArgument()) {
3654 // FIXME: Technically specifying a precision or field width here
3655 // makes no sense. Worth issuing a warning at some point.
3656 return true;
3657 }
3658
3659 // Consume the argument.
3660 unsigned argIndex = FS.getArgIndex();
3661 if (argIndex < NumDataArgs) {
3662 // The check to see if the argIndex is valid will come later.
3663 // We set the bit here because we may exit early from this
3664 // function if we encounter some other error.
3665 CoveredArgs.set(argIndex);
3666 }
3667
Ted Kremenek4407ea42010-07-20 20:04:47 +00003668 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003669 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003670 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3671 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003672 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003673 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003674 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003675 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3676 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003677
Jordan Rose92303592012-09-08 04:00:03 +00003678 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3679 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3680
Ted Kremenek02087932010-07-16 02:11:22 +00003681 // The remaining checks depend on the data arguments.
3682 if (HasVAListArg)
3683 return true;
3684
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003685 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003686 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003687
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003688 // Check that the argument type matches the format specifier.
3689 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003690 if (!Ex)
3691 return true;
3692
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003693 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3694 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003695 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003696 bool success = fixedFS.fixType(Ex->getType(),
3697 Ex->IgnoreImpCasts()->getType(),
3698 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003699
3700 if (success) {
3701 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003702 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003703 llvm::raw_svector_ostream os(buf);
3704 fixedFS.toString(os);
3705
3706 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003707 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3708 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003709 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003710 Ex->getLocStart(),
3711 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003712 getSpecifierRange(startSpecifier, specifierLen),
3713 FixItHint::CreateReplacement(
3714 getSpecifierRange(startSpecifier, specifierLen),
3715 os.str()));
3716 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003717 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003718 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3719 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003720 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003721 Ex->getLocStart(),
3722 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003723 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003724 }
3725 }
3726
Ted Kremenek02087932010-07-16 02:11:22 +00003727 return true;
3728}
3729
3730void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003731 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003732 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003733 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003734 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003735 bool inFunctionCall, VariadicCallType CallType,
3736 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003737
Ted Kremenekab278de2010-01-28 23:39:18 +00003738 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003739 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003740 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003741 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003742 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3743 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003744 return;
3745 }
Ted Kremenek02087932010-07-16 02:11:22 +00003746
Ted Kremenekab278de2010-01-28 23:39:18 +00003747 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003748 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003749 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003750 // Account for cases where the string literal is truncated in a declaration.
3751 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3752 assert(T && "String literal not of constant array type!");
3753 size_t TypeSize = T->getSize().getZExtValue();
3754 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003755 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003756
3757 // Emit a warning if the string literal is truncated and does not contain an
3758 // embedded null character.
3759 if (TypeSize <= StrRef.size() &&
3760 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3761 CheckFormatHandler::EmitFormatDiagnostic(
3762 *this, inFunctionCall, Args[format_idx],
3763 PDiag(diag::warn_printf_format_string_not_null_terminated),
3764 FExpr->getLocStart(),
3765 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3766 return;
3767 }
3768
Ted Kremenekab278de2010-01-28 23:39:18 +00003769 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003770 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003771 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003772 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003773 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3774 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003775 return;
3776 }
Ted Kremenek02087932010-07-16 02:11:22 +00003777
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003778 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003779 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003780 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003781 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003782 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003783
Hans Wennborg23926bd2011-12-15 10:25:47 +00003784 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003785 getLangOpts(),
3786 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003787 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003788 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003789 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003790 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003791 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003792
Hans Wennborg23926bd2011-12-15 10:25:47 +00003793 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003794 getLangOpts(),
3795 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003796 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003797 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003798}
3799
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003800bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
3801 // Str - The format string. NOTE: this is NOT null-terminated!
3802 StringRef StrRef = FExpr->getString();
3803 const char *Str = StrRef.data();
3804 // Account for cases where the string literal is truncated in a declaration.
3805 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3806 assert(T && "String literal not of constant array type!");
3807 size_t TypeSize = T->getSize().getZExtValue();
3808 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3809 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
3810 getLangOpts(),
3811 Context.getTargetInfo());
3812}
3813
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003814//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3815
3816// Returns the related absolute value function that is larger, of 0 if one
3817// does not exist.
3818static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3819 switch (AbsFunction) {
3820 default:
3821 return 0;
3822
3823 case Builtin::BI__builtin_abs:
3824 return Builtin::BI__builtin_labs;
3825 case Builtin::BI__builtin_labs:
3826 return Builtin::BI__builtin_llabs;
3827 case Builtin::BI__builtin_llabs:
3828 return 0;
3829
3830 case Builtin::BI__builtin_fabsf:
3831 return Builtin::BI__builtin_fabs;
3832 case Builtin::BI__builtin_fabs:
3833 return Builtin::BI__builtin_fabsl;
3834 case Builtin::BI__builtin_fabsl:
3835 return 0;
3836
3837 case Builtin::BI__builtin_cabsf:
3838 return Builtin::BI__builtin_cabs;
3839 case Builtin::BI__builtin_cabs:
3840 return Builtin::BI__builtin_cabsl;
3841 case Builtin::BI__builtin_cabsl:
3842 return 0;
3843
3844 case Builtin::BIabs:
3845 return Builtin::BIlabs;
3846 case Builtin::BIlabs:
3847 return Builtin::BIllabs;
3848 case Builtin::BIllabs:
3849 return 0;
3850
3851 case Builtin::BIfabsf:
3852 return Builtin::BIfabs;
3853 case Builtin::BIfabs:
3854 return Builtin::BIfabsl;
3855 case Builtin::BIfabsl:
3856 return 0;
3857
3858 case Builtin::BIcabsf:
3859 return Builtin::BIcabs;
3860 case Builtin::BIcabs:
3861 return Builtin::BIcabsl;
3862 case Builtin::BIcabsl:
3863 return 0;
3864 }
3865}
3866
3867// Returns the argument type of the absolute value function.
3868static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3869 unsigned AbsType) {
3870 if (AbsType == 0)
3871 return QualType();
3872
3873 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3874 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3875 if (Error != ASTContext::GE_None)
3876 return QualType();
3877
3878 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3879 if (!FT)
3880 return QualType();
3881
3882 if (FT->getNumParams() != 1)
3883 return QualType();
3884
3885 return FT->getParamType(0);
3886}
3887
3888// Returns the best absolute value function, or zero, based on type and
3889// current absolute value function.
3890static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3891 unsigned AbsFunctionKind) {
3892 unsigned BestKind = 0;
3893 uint64_t ArgSize = Context.getTypeSize(ArgType);
3894 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3895 Kind = getLargerAbsoluteValueFunction(Kind)) {
3896 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3897 if (Context.getTypeSize(ParamType) >= ArgSize) {
3898 if (BestKind == 0)
3899 BestKind = Kind;
3900 else if (Context.hasSameType(ParamType, ArgType)) {
3901 BestKind = Kind;
3902 break;
3903 }
3904 }
3905 }
3906 return BestKind;
3907}
3908
3909enum AbsoluteValueKind {
3910 AVK_Integer,
3911 AVK_Floating,
3912 AVK_Complex
3913};
3914
3915static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3916 if (T->isIntegralOrEnumerationType())
3917 return AVK_Integer;
3918 if (T->isRealFloatingType())
3919 return AVK_Floating;
3920 if (T->isAnyComplexType())
3921 return AVK_Complex;
3922
3923 llvm_unreachable("Type not integer, floating, or complex");
3924}
3925
3926// Changes the absolute value function to a different type. Preserves whether
3927// the function is a builtin.
3928static unsigned changeAbsFunction(unsigned AbsKind,
3929 AbsoluteValueKind ValueKind) {
3930 switch (ValueKind) {
3931 case AVK_Integer:
3932 switch (AbsKind) {
3933 default:
3934 return 0;
3935 case Builtin::BI__builtin_fabsf:
3936 case Builtin::BI__builtin_fabs:
3937 case Builtin::BI__builtin_fabsl:
3938 case Builtin::BI__builtin_cabsf:
3939 case Builtin::BI__builtin_cabs:
3940 case Builtin::BI__builtin_cabsl:
3941 return Builtin::BI__builtin_abs;
3942 case Builtin::BIfabsf:
3943 case Builtin::BIfabs:
3944 case Builtin::BIfabsl:
3945 case Builtin::BIcabsf:
3946 case Builtin::BIcabs:
3947 case Builtin::BIcabsl:
3948 return Builtin::BIabs;
3949 }
3950 case AVK_Floating:
3951 switch (AbsKind) {
3952 default:
3953 return 0;
3954 case Builtin::BI__builtin_abs:
3955 case Builtin::BI__builtin_labs:
3956 case Builtin::BI__builtin_llabs:
3957 case Builtin::BI__builtin_cabsf:
3958 case Builtin::BI__builtin_cabs:
3959 case Builtin::BI__builtin_cabsl:
3960 return Builtin::BI__builtin_fabsf;
3961 case Builtin::BIabs:
3962 case Builtin::BIlabs:
3963 case Builtin::BIllabs:
3964 case Builtin::BIcabsf:
3965 case Builtin::BIcabs:
3966 case Builtin::BIcabsl:
3967 return Builtin::BIfabsf;
3968 }
3969 case AVK_Complex:
3970 switch (AbsKind) {
3971 default:
3972 return 0;
3973 case Builtin::BI__builtin_abs:
3974 case Builtin::BI__builtin_labs:
3975 case Builtin::BI__builtin_llabs:
3976 case Builtin::BI__builtin_fabsf:
3977 case Builtin::BI__builtin_fabs:
3978 case Builtin::BI__builtin_fabsl:
3979 return Builtin::BI__builtin_cabsf;
3980 case Builtin::BIabs:
3981 case Builtin::BIlabs:
3982 case Builtin::BIllabs:
3983 case Builtin::BIfabsf:
3984 case Builtin::BIfabs:
3985 case Builtin::BIfabsl:
3986 return Builtin::BIcabsf;
3987 }
3988 }
3989 llvm_unreachable("Unable to convert function");
3990}
3991
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003992static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003993 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3994 if (!FnInfo)
3995 return 0;
3996
3997 switch (FDecl->getBuiltinID()) {
3998 default:
3999 return 0;
4000 case Builtin::BI__builtin_abs:
4001 case Builtin::BI__builtin_fabs:
4002 case Builtin::BI__builtin_fabsf:
4003 case Builtin::BI__builtin_fabsl:
4004 case Builtin::BI__builtin_labs:
4005 case Builtin::BI__builtin_llabs:
4006 case Builtin::BI__builtin_cabs:
4007 case Builtin::BI__builtin_cabsf:
4008 case Builtin::BI__builtin_cabsl:
4009 case Builtin::BIabs:
4010 case Builtin::BIlabs:
4011 case Builtin::BIllabs:
4012 case Builtin::BIfabs:
4013 case Builtin::BIfabsf:
4014 case Builtin::BIfabsl:
4015 case Builtin::BIcabs:
4016 case Builtin::BIcabsf:
4017 case Builtin::BIcabsl:
4018 return FDecl->getBuiltinID();
4019 }
4020 llvm_unreachable("Unknown Builtin type");
4021}
4022
4023// If the replacement is valid, emit a note with replacement function.
4024// Additionally, suggest including the proper header if not already included.
4025static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004026 unsigned AbsKind, QualType ArgType) {
4027 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004028 const char *HeaderName = nullptr;
4029 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004030 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4031 FunctionName = "std::abs";
4032 if (ArgType->isIntegralOrEnumerationType()) {
4033 HeaderName = "cstdlib";
4034 } else if (ArgType->isRealFloatingType()) {
4035 HeaderName = "cmath";
4036 } else {
4037 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004038 }
Richard Trieubeffb832014-04-15 23:47:53 +00004039
4040 // Lookup all std::abs
4041 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004042 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004043 R.suppressDiagnostics();
4044 S.LookupQualifiedName(R, Std);
4045
4046 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004047 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004048 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4049 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4050 } else {
4051 FDecl = dyn_cast<FunctionDecl>(I);
4052 }
4053 if (!FDecl)
4054 continue;
4055
4056 // Found std::abs(), check that they are the right ones.
4057 if (FDecl->getNumParams() != 1)
4058 continue;
4059
4060 // Check that the parameter type can handle the argument.
4061 QualType ParamType = FDecl->getParamDecl(0)->getType();
4062 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4063 S.Context.getTypeSize(ArgType) <=
4064 S.Context.getTypeSize(ParamType)) {
4065 // Found a function, don't need the header hint.
4066 EmitHeaderHint = false;
4067 break;
4068 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004069 }
Richard Trieubeffb832014-04-15 23:47:53 +00004070 }
4071 } else {
4072 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4073 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4074
4075 if (HeaderName) {
4076 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4077 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4078 R.suppressDiagnostics();
4079 S.LookupName(R, S.getCurScope());
4080
4081 if (R.isSingleResult()) {
4082 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4083 if (FD && FD->getBuiltinID() == AbsKind) {
4084 EmitHeaderHint = false;
4085 } else {
4086 return;
4087 }
4088 } else if (!R.empty()) {
4089 return;
4090 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004091 }
4092 }
4093
4094 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004095 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004096
Richard Trieubeffb832014-04-15 23:47:53 +00004097 if (!HeaderName)
4098 return;
4099
4100 if (!EmitHeaderHint)
4101 return;
4102
Alp Toker5d96e0a2014-07-11 20:53:51 +00004103 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4104 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004105}
4106
4107static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4108 if (!FDecl)
4109 return false;
4110
4111 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4112 return false;
4113
4114 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4115
4116 while (ND && ND->isInlineNamespace()) {
4117 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004118 }
Richard Trieubeffb832014-04-15 23:47:53 +00004119
4120 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4121 return false;
4122
4123 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4124 return false;
4125
4126 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004127}
4128
4129// Warn when using the wrong abs() function.
4130void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4131 const FunctionDecl *FDecl,
4132 IdentifierInfo *FnInfo) {
4133 if (Call->getNumArgs() != 1)
4134 return;
4135
4136 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004137 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4138 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004139 return;
4140
4141 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4142 QualType ParamType = Call->getArg(0)->getType();
4143
Alp Toker5d96e0a2014-07-11 20:53:51 +00004144 // Unsigned types cannot be negative. Suggest removing the absolute value
4145 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004146 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004147 const char *FunctionName =
4148 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004149 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4150 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004151 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004152 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4153 return;
4154 }
4155
Richard Trieubeffb832014-04-15 23:47:53 +00004156 // std::abs has overloads which prevent most of the absolute value problems
4157 // from occurring.
4158 if (IsStdAbs)
4159 return;
4160
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004161 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4162 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4163
4164 // The argument and parameter are the same kind. Check if they are the right
4165 // size.
4166 if (ArgValueKind == ParamValueKind) {
4167 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4168 return;
4169
4170 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4171 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4172 << FDecl << ArgType << ParamType;
4173
4174 if (NewAbsKind == 0)
4175 return;
4176
4177 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004178 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004179 return;
4180 }
4181
4182 // ArgValueKind != ParamValueKind
4183 // The wrong type of absolute value function was used. Attempt to find the
4184 // proper one.
4185 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4186 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4187 if (NewAbsKind == 0)
4188 return;
4189
4190 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4191 << FDecl << ParamValueKind << ArgValueKind;
4192
4193 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004194 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004195 return;
4196}
4197
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004198//===--- CHECK: Standard memory functions ---------------------------------===//
4199
Nico Weber0e6daef2013-12-26 23:38:39 +00004200/// \brief Takes the expression passed to the size_t parameter of functions
4201/// such as memcmp, strncat, etc and warns if it's a comparison.
4202///
4203/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4204static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4205 IdentifierInfo *FnName,
4206 SourceLocation FnLoc,
4207 SourceLocation RParenLoc) {
4208 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4209 if (!Size)
4210 return false;
4211
4212 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4213 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4214 return false;
4215
Nico Weber0e6daef2013-12-26 23:38:39 +00004216 SourceRange SizeRange = Size->getSourceRange();
4217 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4218 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004219 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004220 << FnName << FixItHint::CreateInsertion(
4221 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004222 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004223 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004224 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004225 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4226 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004227
4228 return true;
4229}
4230
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004231/// \brief Determine whether the given type is or contains a dynamic class type
4232/// (e.g., whether it has a vtable).
4233static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4234 bool &IsContained) {
4235 // Look through array types while ignoring qualifiers.
4236 const Type *Ty = T->getBaseElementTypeUnsafe();
4237 IsContained = false;
4238
4239 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4240 RD = RD ? RD->getDefinition() : nullptr;
4241 if (!RD)
4242 return nullptr;
4243
4244 if (RD->isDynamicClass())
4245 return RD;
4246
4247 // Check all the fields. If any bases were dynamic, the class is dynamic.
4248 // It's impossible for a class to transitively contain itself by value, so
4249 // infinite recursion is impossible.
4250 for (auto *FD : RD->fields()) {
4251 bool SubContained;
4252 if (const CXXRecordDecl *ContainedRD =
4253 getContainedDynamicClass(FD->getType(), SubContained)) {
4254 IsContained = true;
4255 return ContainedRD;
4256 }
4257 }
4258
4259 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004260}
4261
Chandler Carruth889ed862011-06-21 23:04:20 +00004262/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004263/// otherwise returns NULL.
4264static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004265 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004266 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4267 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4268 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004269
Craig Topperc3ec1492014-05-26 06:22:03 +00004270 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004271}
4272
Chandler Carruth889ed862011-06-21 23:04:20 +00004273/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004274static QualType getSizeOfArgType(const Expr* E) {
4275 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4276 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4277 if (SizeOf->getKind() == clang::UETT_SizeOf)
4278 return SizeOf->getTypeOfArgument();
4279
4280 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004281}
4282
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004283/// \brief Check for dangerous or invalid arguments to memset().
4284///
Chandler Carruthac687262011-06-03 06:23:57 +00004285/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004286/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4287/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004288///
4289/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004290void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004291 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004292 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004293 assert(BId != 0);
4294
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004295 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004296 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004297 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004298 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004299 return;
4300
Anna Zaks22122702012-01-17 00:37:07 +00004301 unsigned LastArg = (BId == Builtin::BImemset ||
4302 BId == Builtin::BIstrndup ? 1 : 2);
4303 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004304 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004305
Nico Weber0e6daef2013-12-26 23:38:39 +00004306 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4307 Call->getLocStart(), Call->getRParenLoc()))
4308 return;
4309
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004310 // We have special checking when the length is a sizeof expression.
4311 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4312 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4313 llvm::FoldingSetNodeID SizeOfArgID;
4314
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004315 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4316 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004317 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004318
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004319 QualType DestTy = Dest->getType();
4320 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4321 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004322
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004323 // Never warn about void type pointers. This can be used to suppress
4324 // false positives.
4325 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004326 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004327
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004328 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4329 // actually comparing the expressions for equality. Because computing the
4330 // expression IDs can be expensive, we only do this if the diagnostic is
4331 // enabled.
4332 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004333 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4334 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004335 // We only compute IDs for expressions if the warning is enabled, and
4336 // cache the sizeof arg's ID.
4337 if (SizeOfArgID == llvm::FoldingSetNodeID())
4338 SizeOfArg->Profile(SizeOfArgID, Context, true);
4339 llvm::FoldingSetNodeID DestID;
4340 Dest->Profile(DestID, Context, true);
4341 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004342 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4343 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004344 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004345 StringRef ReadableName = FnName->getName();
4346
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004347 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004348 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004349 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004350 if (!PointeeTy->isIncompleteType() &&
4351 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004352 ActionIdx = 2; // If the pointee's size is sizeof(char),
4353 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004354
4355 // If the function is defined as a builtin macro, do not show macro
4356 // expansion.
4357 SourceLocation SL = SizeOfArg->getExprLoc();
4358 SourceRange DSR = Dest->getSourceRange();
4359 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004360 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004361
4362 if (SM.isMacroArgExpansion(SL)) {
4363 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4364 SL = SM.getSpellingLoc(SL);
4365 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4366 SM.getSpellingLoc(DSR.getEnd()));
4367 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4368 SM.getSpellingLoc(SSR.getEnd()));
4369 }
4370
Anna Zaksd08d9152012-05-30 23:14:52 +00004371 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004372 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004373 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004374 << PointeeTy
4375 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004376 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004377 << SSR);
4378 DiagRuntimeBehavior(SL, SizeOfArg,
4379 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4380 << ActionIdx
4381 << SSR);
4382
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004383 break;
4384 }
4385 }
4386
4387 // Also check for cases where the sizeof argument is the exact same
4388 // type as the memory argument, and where it points to a user-defined
4389 // record type.
4390 if (SizeOfArgTy != QualType()) {
4391 if (PointeeTy->isRecordType() &&
4392 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4393 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4394 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4395 << FnName << SizeOfArgTy << ArgIdx
4396 << PointeeTy << Dest->getSourceRange()
4397 << LenExpr->getSourceRange());
4398 break;
4399 }
Nico Weberc5e73862011-06-14 16:14:58 +00004400 }
4401
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004402 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004403 bool IsContained;
4404 if (const CXXRecordDecl *ContainedRD =
4405 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004406
4407 unsigned OperationType = 0;
4408 // "overwritten" if we're warning about the destination for any call
4409 // but memcmp; otherwise a verb appropriate to the call.
4410 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4411 if (BId == Builtin::BImemcpy)
4412 OperationType = 1;
4413 else if(BId == Builtin::BImemmove)
4414 OperationType = 2;
4415 else if (BId == Builtin::BImemcmp)
4416 OperationType = 3;
4417 }
4418
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004419 DiagRuntimeBehavior(
4420 Dest->getExprLoc(), Dest,
4421 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004422 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004423 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004424 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004425 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4426 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004427 DiagRuntimeBehavior(
4428 Dest->getExprLoc(), Dest,
4429 PDiag(diag::warn_arc_object_memaccess)
4430 << ArgIdx << FnName << PointeeTy
4431 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004432 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004433 continue;
John McCall31168b02011-06-15 23:02:42 +00004434
4435 DiagRuntimeBehavior(
4436 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004437 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004438 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4439 break;
4440 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004441 }
4442}
4443
Ted Kremenek6865f772011-08-18 20:55:45 +00004444// A little helper routine: ignore addition and subtraction of integer literals.
4445// This intentionally does not ignore all integer constant expressions because
4446// we don't want to remove sizeof().
4447static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4448 Ex = Ex->IgnoreParenCasts();
4449
4450 for (;;) {
4451 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4452 if (!BO || !BO->isAdditiveOp())
4453 break;
4454
4455 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4456 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4457
4458 if (isa<IntegerLiteral>(RHS))
4459 Ex = LHS;
4460 else if (isa<IntegerLiteral>(LHS))
4461 Ex = RHS;
4462 else
4463 break;
4464 }
4465
4466 return Ex;
4467}
4468
Anna Zaks13b08572012-08-08 21:42:23 +00004469static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4470 ASTContext &Context) {
4471 // Only handle constant-sized or VLAs, but not flexible members.
4472 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4473 // Only issue the FIXIT for arrays of size > 1.
4474 if (CAT->getSize().getSExtValue() <= 1)
4475 return false;
4476 } else if (!Ty->isVariableArrayType()) {
4477 return false;
4478 }
4479 return true;
4480}
4481
Ted Kremenek6865f772011-08-18 20:55:45 +00004482// Warn if the user has made the 'size' argument to strlcpy or strlcat
4483// be the size of the source, instead of the destination.
4484void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4485 IdentifierInfo *FnName) {
4486
4487 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004488 unsigned NumArgs = Call->getNumArgs();
4489 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004490 return;
4491
4492 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4493 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004494 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004495
4496 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4497 Call->getLocStart(), Call->getRParenLoc()))
4498 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004499
4500 // Look for 'strlcpy(dst, x, sizeof(x))'
4501 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4502 CompareWithSrc = Ex;
4503 else {
4504 // Look for 'strlcpy(dst, x, strlen(x))'
4505 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004506 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4507 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004508 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4509 }
4510 }
4511
4512 if (!CompareWithSrc)
4513 return;
4514
4515 // Determine if the argument to sizeof/strlen is equal to the source
4516 // argument. In principle there's all kinds of things you could do
4517 // here, for instance creating an == expression and evaluating it with
4518 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4519 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4520 if (!SrcArgDRE)
4521 return;
4522
4523 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4524 if (!CompareWithSrcDRE ||
4525 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4526 return;
4527
4528 const Expr *OriginalSizeArg = Call->getArg(2);
4529 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4530 << OriginalSizeArg->getSourceRange() << FnName;
4531
4532 // Output a FIXIT hint if the destination is an array (rather than a
4533 // pointer to an array). This could be enhanced to handle some
4534 // pointers if we know the actual size, like if DstArg is 'array+2'
4535 // we could say 'sizeof(array)-2'.
4536 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004537 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004538 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004539
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004540 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004541 llvm::raw_svector_ostream OS(sizeString);
4542 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004543 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004544 OS << ")";
4545
4546 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4547 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4548 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004549}
4550
Anna Zaks314cd092012-02-01 19:08:57 +00004551/// Check if two expressions refer to the same declaration.
4552static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4553 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4554 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4555 return D1->getDecl() == D2->getDecl();
4556 return false;
4557}
4558
4559static const Expr *getStrlenExprArg(const Expr *E) {
4560 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4561 const FunctionDecl *FD = CE->getDirectCallee();
4562 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004563 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004564 return CE->getArg(0)->IgnoreParenCasts();
4565 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004566 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004567}
4568
4569// Warn on anti-patterns as the 'size' argument to strncat.
4570// The correct size argument should look like following:
4571// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4572void Sema::CheckStrncatArguments(const CallExpr *CE,
4573 IdentifierInfo *FnName) {
4574 // Don't crash if the user has the wrong number of arguments.
4575 if (CE->getNumArgs() < 3)
4576 return;
4577 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4578 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4579 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4580
Nico Weber0e6daef2013-12-26 23:38:39 +00004581 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4582 CE->getRParenLoc()))
4583 return;
4584
Anna Zaks314cd092012-02-01 19:08:57 +00004585 // Identify common expressions, which are wrongly used as the size argument
4586 // to strncat and may lead to buffer overflows.
4587 unsigned PatternType = 0;
4588 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4589 // - sizeof(dst)
4590 if (referToTheSameDecl(SizeOfArg, DstArg))
4591 PatternType = 1;
4592 // - sizeof(src)
4593 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4594 PatternType = 2;
4595 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4596 if (BE->getOpcode() == BO_Sub) {
4597 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4598 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4599 // - sizeof(dst) - strlen(dst)
4600 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4601 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4602 PatternType = 1;
4603 // - sizeof(src) - (anything)
4604 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4605 PatternType = 2;
4606 }
4607 }
4608
4609 if (PatternType == 0)
4610 return;
4611
Anna Zaks5069aa32012-02-03 01:27:37 +00004612 // Generate the diagnostic.
4613 SourceLocation SL = LenArg->getLocStart();
4614 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004615 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004616
4617 // If the function is defined as a builtin macro, do not show macro expansion.
4618 if (SM.isMacroArgExpansion(SL)) {
4619 SL = SM.getSpellingLoc(SL);
4620 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4621 SM.getSpellingLoc(SR.getEnd()));
4622 }
4623
Anna Zaks13b08572012-08-08 21:42:23 +00004624 // Check if the destination is an array (rather than a pointer to an array).
4625 QualType DstTy = DstArg->getType();
4626 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4627 Context);
4628 if (!isKnownSizeArray) {
4629 if (PatternType == 1)
4630 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4631 else
4632 Diag(SL, diag::warn_strncat_src_size) << SR;
4633 return;
4634 }
4635
Anna Zaks314cd092012-02-01 19:08:57 +00004636 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004637 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004638 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004639 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004640
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004641 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004642 llvm::raw_svector_ostream OS(sizeString);
4643 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004644 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004645 OS << ") - ";
4646 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004647 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004648 OS << ") - 1";
4649
Anna Zaks5069aa32012-02-03 01:27:37 +00004650 Diag(SL, diag::note_strncat_wrong_size)
4651 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004652}
4653
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004654//===--- CHECK: Return Address of Stack Variable --------------------------===//
4655
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004656static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4657 Decl *ParentDecl);
4658static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4659 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004660
4661/// CheckReturnStackAddr - Check if a return statement returns the address
4662/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004663static void
4664CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4665 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004666
Craig Topperc3ec1492014-05-26 06:22:03 +00004667 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004668 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004669
4670 // Perform checking for returned stack addresses, local blocks,
4671 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004672 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004673 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004674 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004675 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004676 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004677 }
4678
Craig Topperc3ec1492014-05-26 06:22:03 +00004679 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004680 return; // Nothing suspicious was found.
4681
4682 SourceLocation diagLoc;
4683 SourceRange diagRange;
4684 if (refVars.empty()) {
4685 diagLoc = stackE->getLocStart();
4686 diagRange = stackE->getSourceRange();
4687 } else {
4688 // We followed through a reference variable. 'stackE' contains the
4689 // problematic expression but we will warn at the return statement pointing
4690 // at the reference variable. We will later display the "trail" of
4691 // reference variables using notes.
4692 diagLoc = refVars[0]->getLocStart();
4693 diagRange = refVars[0]->getSourceRange();
4694 }
4695
4696 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004697 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004698 : diag::warn_ret_stack_addr)
4699 << DR->getDecl()->getDeclName() << diagRange;
4700 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004701 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004702 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004703 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004704 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004705 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4706 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004707 << diagRange;
4708 }
4709
4710 // Display the "trail" of reference variables that we followed until we
4711 // found the problematic expression using notes.
4712 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4713 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4714 // If this var binds to another reference var, show the range of the next
4715 // var, otherwise the var binds to the problematic expression, in which case
4716 // show the range of the expression.
4717 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4718 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004719 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4720 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004721 }
4722}
4723
4724/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4725/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004726/// to a location on the stack, a local block, an address of a label, or a
4727/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004728/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004729/// encounter a subexpression that (1) clearly does not lead to one of the
4730/// above problematic expressions (2) is something we cannot determine leads to
4731/// a problematic expression based on such local checking.
4732///
4733/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4734/// the expression that they point to. Such variables are added to the
4735/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004736///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004737/// EvalAddr processes expressions that are pointers that are used as
4738/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004739/// At the base case of the recursion is a check for the above problematic
4740/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004741///
4742/// This implementation handles:
4743///
4744/// * pointer-to-pointer casts
4745/// * implicit conversions from array references to pointers
4746/// * taking the address of fields
4747/// * arbitrary interplay between "&" and "*" operators
4748/// * pointer arithmetic from an address of a stack variable
4749/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004750static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4751 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004752 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004753 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004754
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004755 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004756 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004757 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004758 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004759 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004760
Peter Collingbourne91147592011-04-15 00:35:48 +00004761 E = E->IgnoreParens();
4762
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004763 // Our "symbolic interpreter" is just a dispatch off the currently
4764 // viewed AST node. We then recursively traverse the AST by calling
4765 // EvalAddr and EvalVal appropriately.
4766 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004767 case Stmt::DeclRefExprClass: {
4768 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4769
Richard Smith40f08eb2014-01-30 22:05:38 +00004770 // If we leave the immediate function, the lifetime isn't about to end.
4771 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004772 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004773
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004774 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4775 // If this is a reference variable, follow through to the expression that
4776 // it points to.
4777 if (V->hasLocalStorage() &&
4778 V->getType()->isReferenceType() && V->hasInit()) {
4779 // Add the reference variable to the "trail".
4780 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004781 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004782 }
4783
Craig Topperc3ec1492014-05-26 06:22:03 +00004784 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004785 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004786
Chris Lattner934edb22007-12-28 05:31:15 +00004787 case Stmt::UnaryOperatorClass: {
4788 // The only unary operator that make sense to handle here
4789 // is AddrOf. All others don't make sense as pointers.
4790 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004791
John McCalle3027922010-08-25 11:45:40 +00004792 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004793 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004794 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004795 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004796 }
Mike Stump11289f42009-09-09 15:08:12 +00004797
Chris Lattner934edb22007-12-28 05:31:15 +00004798 case Stmt::BinaryOperatorClass: {
4799 // Handle pointer arithmetic. All other binary operators are not valid
4800 // in this context.
4801 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004802 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004803
John McCalle3027922010-08-25 11:45:40 +00004804 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004805 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattner934edb22007-12-28 05:31:15 +00004807 Expr *Base = B->getLHS();
4808
4809 // Determine which argument is the real pointer base. It could be
4810 // the RHS argument instead of the LHS.
4811 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004812
Chris Lattner934edb22007-12-28 05:31:15 +00004813 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004814 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004815 }
Steve Naroff2752a172008-09-10 19:17:48 +00004816
Chris Lattner934edb22007-12-28 05:31:15 +00004817 // For conditional operators we need to see if either the LHS or RHS are
4818 // valid DeclRefExpr*s. If one of them is valid, we return it.
4819 case Stmt::ConditionalOperatorClass: {
4820 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004821
Chris Lattner934edb22007-12-28 05:31:15 +00004822 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004823 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4824 if (Expr *LHSExpr = C->getLHS()) {
4825 // In C++, we can have a throw-expression, which has 'void' type.
4826 if (!LHSExpr->getType()->isVoidType())
4827 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004828 return LHS;
4829 }
Chris Lattner934edb22007-12-28 05:31:15 +00004830
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004831 // In C++, we can have a throw-expression, which has 'void' type.
4832 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004833 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004834
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004835 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004836 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004837
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004838 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004839 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004840 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004841 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004842
4843 case Stmt::AddrLabelExprClass:
4844 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004845
John McCall28fc7092011-11-10 05:35:25 +00004846 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004847 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4848 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004849
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004850 // For casts, we need to handle conversions from arrays to
4851 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004852 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004853 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004854 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004855 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004856 case Stmt::CXXStaticCastExprClass:
4857 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004858 case Stmt::CXXConstCastExprClass:
4859 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004860 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4861 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004862 case CK_LValueToRValue:
4863 case CK_NoOp:
4864 case CK_BaseToDerived:
4865 case CK_DerivedToBase:
4866 case CK_UncheckedDerivedToBase:
4867 case CK_Dynamic:
4868 case CK_CPointerToObjCPointerCast:
4869 case CK_BlockPointerToObjCPointerCast:
4870 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004871 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004872
4873 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004874 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004875
Richard Trieudadefde2014-07-02 04:39:38 +00004876 case CK_BitCast:
4877 if (SubExpr->getType()->isAnyPointerType() ||
4878 SubExpr->getType()->isBlockPointerType() ||
4879 SubExpr->getType()->isObjCQualifiedIdType())
4880 return EvalAddr(SubExpr, refVars, ParentDecl);
4881 else
4882 return nullptr;
4883
Eli Friedman8195ad72012-02-23 23:04:32 +00004884 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004885 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004886 }
Chris Lattner934edb22007-12-28 05:31:15 +00004887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
Douglas Gregorfe314812011-06-21 17:03:29 +00004889 case Stmt::MaterializeTemporaryExprClass:
4890 if (Expr *Result = EvalAddr(
4891 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004892 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004893 return Result;
4894
4895 return E;
4896
Chris Lattner934edb22007-12-28 05:31:15 +00004897 // Everything else: we simply don't reason about them.
4898 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004899 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004900 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004901}
Mike Stump11289f42009-09-09 15:08:12 +00004902
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004903
4904/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4905/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004906static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4907 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004908do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004909 // We should only be called for evaluating non-pointer expressions, or
4910 // expressions with a pointer type that are not used as references but instead
4911 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004912
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004913 // Our "symbolic interpreter" is just a dispatch off the currently
4914 // viewed AST node. We then recursively traverse the AST by calling
4915 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004916
4917 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004918 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004919 case Stmt::ImplicitCastExprClass: {
4920 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004921 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004922 E = IE->getSubExpr();
4923 continue;
4924 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004925 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004926 }
4927
John McCall28fc7092011-11-10 05:35:25 +00004928 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004929 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004930
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004931 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004932 // When we hit a DeclRefExpr we are looking at code that refers to a
4933 // variable's name. If it's not a reference variable we check if it has
4934 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004935 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004936
Richard Smith40f08eb2014-01-30 22:05:38 +00004937 // If we leave the immediate function, the lifetime isn't about to end.
4938 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004939 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004940
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004941 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4942 // Check if it refers to itself, e.g. "int& i = i;".
4943 if (V == ParentDecl)
4944 return DR;
4945
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004946 if (V->hasLocalStorage()) {
4947 if (!V->getType()->isReferenceType())
4948 return DR;
4949
4950 // Reference variable, follow through to the expression that
4951 // it points to.
4952 if (V->hasInit()) {
4953 // Add the reference variable to the "trail".
4954 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004955 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004956 }
4957 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004961 }
Mike Stump11289f42009-09-09 15:08:12 +00004962
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004963 case Stmt::UnaryOperatorClass: {
4964 // The only unary operator that make sense to handle here
4965 // is Deref. All others don't resolve to a "name." This includes
4966 // handling all sorts of rvalues passed to a unary operator.
4967 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004968
John McCalle3027922010-08-25 11:45:40 +00004969 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004970 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004971
Craig Topperc3ec1492014-05-26 06:22:03 +00004972 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004973 }
Mike Stump11289f42009-09-09 15:08:12 +00004974
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004975 case Stmt::ArraySubscriptExprClass: {
4976 // Array subscripts are potential references to data on the stack. We
4977 // retrieve the DeclRefExpr* for the array variable if it indeed
4978 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004979 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004980 }
Mike Stump11289f42009-09-09 15:08:12 +00004981
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004982 case Stmt::ConditionalOperatorClass: {
4983 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004984 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004985 ConditionalOperator *C = cast<ConditionalOperator>(E);
4986
Anders Carlsson801c5c72007-11-30 19:04:31 +00004987 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004988 if (Expr *LHSExpr = C->getLHS()) {
4989 // In C++, we can have a throw-expression, which has 'void' type.
4990 if (!LHSExpr->getType()->isVoidType())
4991 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4992 return LHS;
4993 }
4994
4995 // In C++, we can have a throw-expression, which has 'void' type.
4996 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004997 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004998
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004999 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005000 }
Mike Stump11289f42009-09-09 15:08:12 +00005001
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005002 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005003 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005004 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005005
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005006 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005007 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005008 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005009
5010 // Check whether the member type is itself a reference, in which case
5011 // we're not going to refer to the member, but to what the member refers to.
5012 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005013 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005014
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005015 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005016 }
Mike Stump11289f42009-09-09 15:08:12 +00005017
Douglas Gregorfe314812011-06-21 17:03:29 +00005018 case Stmt::MaterializeTemporaryExprClass:
5019 if (Expr *Result = EvalVal(
5020 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005021 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005022 return Result;
5023
5024 return E;
5025
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005026 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005027 // Check that we don't return or take the address of a reference to a
5028 // temporary. This is only useful in C++.
5029 if (!E->isTypeDependent() && E->isRValue())
5030 return E;
5031
5032 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005033 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005034 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005035} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005036}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005037
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005038void
5039Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5040 SourceLocation ReturnLoc,
5041 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005042 const AttrVec *Attrs,
5043 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005044 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5045
5046 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005047 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5048 CheckNonNullExpr(*this, RetValExp))
5049 Diag(ReturnLoc, diag::warn_null_ret)
5050 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005051
5052 // C++11 [basic.stc.dynamic.allocation]p4:
5053 // If an allocation function declared with a non-throwing
5054 // exception-specification fails to allocate storage, it shall return
5055 // a null pointer. Any other allocation function that fails to allocate
5056 // storage shall indicate failure only by throwing an exception [...]
5057 if (FD) {
5058 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5059 if (Op == OO_New || Op == OO_Array_New) {
5060 const FunctionProtoType *Proto
5061 = FD->getType()->castAs<FunctionProtoType>();
5062 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5063 CheckNonNullExpr(*this, RetValExp))
5064 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5065 << FD << getLangOpts().CPlusPlus11;
5066 }
5067 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005068}
5069
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005070//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5071
5072/// Check for comparisons of floating point operands using != and ==.
5073/// Issue a warning if these are no self-comparisons, as they are not likely
5074/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005075void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005076 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5077 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005078
5079 // Special case: check for x == x (which is OK).
5080 // Do not emit warnings for such cases.
5081 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5082 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5083 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005084 return;
Mike Stump11289f42009-09-09 15:08:12 +00005085
5086
Ted Kremenekeda40e22007-11-29 00:59:04 +00005087 // Special case: check for comparisons against literals that can be exactly
5088 // represented by APFloat. In such cases, do not emit a warning. This
5089 // is a heuristic: often comparison against such literals are used to
5090 // detect if a value in a variable has not changed. This clearly can
5091 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005092 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5093 if (FLL->isExact())
5094 return;
5095 } else
5096 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5097 if (FLR->isExact())
5098 return;
Mike Stump11289f42009-09-09 15:08:12 +00005099
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005100 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005101 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005102 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005103 return;
Mike Stump11289f42009-09-09 15:08:12 +00005104
David Blaikie1f4ff152012-07-16 20:47:22 +00005105 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005106 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005107 return;
Mike Stump11289f42009-09-09 15:08:12 +00005108
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005109 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005110 Diag(Loc, diag::warn_floatingpoint_eq)
5111 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005112}
John McCallca01b222010-01-04 23:21:16 +00005113
John McCall70aa5392010-01-06 05:24:50 +00005114//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5115//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005116
John McCall70aa5392010-01-06 05:24:50 +00005117namespace {
John McCallca01b222010-01-04 23:21:16 +00005118
John McCall70aa5392010-01-06 05:24:50 +00005119/// Structure recording the 'active' range of an integer-valued
5120/// expression.
5121struct IntRange {
5122 /// The number of bits active in the int.
5123 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005124
John McCall70aa5392010-01-06 05:24:50 +00005125 /// True if the int is known not to have negative values.
5126 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005127
John McCall70aa5392010-01-06 05:24:50 +00005128 IntRange(unsigned Width, bool NonNegative)
5129 : Width(Width), NonNegative(NonNegative)
5130 {}
John McCallca01b222010-01-04 23:21:16 +00005131
John McCall817d4af2010-11-10 23:38:19 +00005132 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005133 static IntRange forBoolType() {
5134 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005135 }
5136
John McCall817d4af2010-11-10 23:38:19 +00005137 /// Returns the range of an opaque value of the given integral type.
5138 static IntRange forValueOfType(ASTContext &C, QualType T) {
5139 return forValueOfCanonicalType(C,
5140 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005141 }
5142
John McCall817d4af2010-11-10 23:38:19 +00005143 /// Returns the range of an opaque value of a canonical integral type.
5144 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005145 assert(T->isCanonicalUnqualified());
5146
5147 if (const VectorType *VT = dyn_cast<VectorType>(T))
5148 T = VT->getElementType().getTypePtr();
5149 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5150 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005151 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5152 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005153
David Majnemer6a426652013-06-07 22:07:20 +00005154 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005155 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005156 EnumDecl *Enum = ET->getDecl();
5157 if (!Enum->isCompleteDefinition())
5158 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005159
David Majnemer6a426652013-06-07 22:07:20 +00005160 unsigned NumPositive = Enum->getNumPositiveBits();
5161 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005162
David Majnemer6a426652013-06-07 22:07:20 +00005163 if (NumNegative == 0)
5164 return IntRange(NumPositive, true/*NonNegative*/);
5165 else
5166 return IntRange(std::max(NumPositive + 1, NumNegative),
5167 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005168 }
John McCall70aa5392010-01-06 05:24:50 +00005169
5170 const BuiltinType *BT = cast<BuiltinType>(T);
5171 assert(BT->isInteger());
5172
5173 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5174 }
5175
John McCall817d4af2010-11-10 23:38:19 +00005176 /// Returns the "target" range of a canonical integral type, i.e.
5177 /// the range of values expressible in the type.
5178 ///
5179 /// This matches forValueOfCanonicalType except that enums have the
5180 /// full range of their type, not the range of their enumerators.
5181 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5182 assert(T->isCanonicalUnqualified());
5183
5184 if (const VectorType *VT = dyn_cast<VectorType>(T))
5185 T = VT->getElementType().getTypePtr();
5186 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5187 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005188 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5189 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005190 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005191 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005192
5193 const BuiltinType *BT = cast<BuiltinType>(T);
5194 assert(BT->isInteger());
5195
5196 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5197 }
5198
5199 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005200 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005201 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005202 L.NonNegative && R.NonNegative);
5203 }
5204
John McCall817d4af2010-11-10 23:38:19 +00005205 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005206 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005207 return IntRange(std::min(L.Width, R.Width),
5208 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005209 }
5210};
5211
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005212static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5213 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005214 if (value.isSigned() && value.isNegative())
5215 return IntRange(value.getMinSignedBits(), false);
5216
5217 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005218 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005219
5220 // isNonNegative() just checks the sign bit without considering
5221 // signedness.
5222 return IntRange(value.getActiveBits(), true);
5223}
5224
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005225static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5226 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005227 if (result.isInt())
5228 return GetValueRange(C, result.getInt(), MaxWidth);
5229
5230 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005231 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5232 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5233 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5234 R = IntRange::join(R, El);
5235 }
John McCall70aa5392010-01-06 05:24:50 +00005236 return R;
5237 }
5238
5239 if (result.isComplexInt()) {
5240 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5241 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5242 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005243 }
5244
5245 // This can happen with lossless casts to intptr_t of "based" lvalues.
5246 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005247 // FIXME: The only reason we need to pass the type in here is to get
5248 // the sign right on this one case. It would be nice if APValue
5249 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005250 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005251 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005252}
John McCall70aa5392010-01-06 05:24:50 +00005253
Eli Friedmane6d33952013-07-08 20:20:06 +00005254static QualType GetExprType(Expr *E) {
5255 QualType Ty = E->getType();
5256 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5257 Ty = AtomicRHS->getValueType();
5258 return Ty;
5259}
5260
John McCall70aa5392010-01-06 05:24:50 +00005261/// Pseudo-evaluate the given integer expression, estimating the
5262/// range of values it might take.
5263///
5264/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005265static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005266 E = E->IgnoreParens();
5267
5268 // Try a full evaluation first.
5269 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005270 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005271 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005272
5273 // I think we only want to look through implicit casts here; if the
5274 // user has an explicit widening cast, we should treat the value as
5275 // being of the new, wider type.
5276 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005277 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005278 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5279
Eli Friedmane6d33952013-07-08 20:20:06 +00005280 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005281
John McCalle3027922010-08-25 11:45:40 +00005282 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005283
John McCall70aa5392010-01-06 05:24:50 +00005284 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005285 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005286 return OutputTypeRange;
5287
5288 IntRange SubRange
5289 = GetExprRange(C, CE->getSubExpr(),
5290 std::min(MaxWidth, OutputTypeRange.Width));
5291
5292 // Bail out if the subexpr's range is as wide as the cast type.
5293 if (SubRange.Width >= OutputTypeRange.Width)
5294 return OutputTypeRange;
5295
5296 // Otherwise, we take the smaller width, and we're non-negative if
5297 // either the output type or the subexpr is.
5298 return IntRange(SubRange.Width,
5299 SubRange.NonNegative || OutputTypeRange.NonNegative);
5300 }
5301
5302 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5303 // If we can fold the condition, just take that operand.
5304 bool CondResult;
5305 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5306 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5307 : CO->getFalseExpr(),
5308 MaxWidth);
5309
5310 // Otherwise, conservatively merge.
5311 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5312 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5313 return IntRange::join(L, R);
5314 }
5315
5316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5317 switch (BO->getOpcode()) {
5318
5319 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005320 case BO_LAnd:
5321 case BO_LOr:
5322 case BO_LT:
5323 case BO_GT:
5324 case BO_LE:
5325 case BO_GE:
5326 case BO_EQ:
5327 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005328 return IntRange::forBoolType();
5329
John McCallc3688382011-07-13 06:35:24 +00005330 // The type of the assignments is the type of the LHS, so the RHS
5331 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005332 case BO_MulAssign:
5333 case BO_DivAssign:
5334 case BO_RemAssign:
5335 case BO_AddAssign:
5336 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005337 case BO_XorAssign:
5338 case BO_OrAssign:
5339 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005340 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005341
John McCallc3688382011-07-13 06:35:24 +00005342 // Simple assignments just pass through the RHS, which will have
5343 // been coerced to the LHS type.
5344 case BO_Assign:
5345 // TODO: bitfields?
5346 return GetExprRange(C, BO->getRHS(), MaxWidth);
5347
John McCall70aa5392010-01-06 05:24:50 +00005348 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005349 case BO_PtrMemD:
5350 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005351 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005352
John McCall2ce81ad2010-01-06 22:07:33 +00005353 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005354 case BO_And:
5355 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005356 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5357 GetExprRange(C, BO->getRHS(), MaxWidth));
5358
John McCall70aa5392010-01-06 05:24:50 +00005359 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005360 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005361 // ...except that we want to treat '1 << (blah)' as logically
5362 // positive. It's an important idiom.
5363 if (IntegerLiteral *I
5364 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5365 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005366 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005367 return IntRange(R.Width, /*NonNegative*/ true);
5368 }
5369 }
5370 // fallthrough
5371
John McCalle3027922010-08-25 11:45:40 +00005372 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005373 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005374
John McCall2ce81ad2010-01-06 22:07:33 +00005375 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005376 case BO_Shr:
5377 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005378 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5379
5380 // If the shift amount is a positive constant, drop the width by
5381 // that much.
5382 llvm::APSInt shift;
5383 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5384 shift.isNonNegative()) {
5385 unsigned zext = shift.getZExtValue();
5386 if (zext >= L.Width)
5387 L.Width = (L.NonNegative ? 0 : 1);
5388 else
5389 L.Width -= zext;
5390 }
5391
5392 return L;
5393 }
5394
5395 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005396 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005397 return GetExprRange(C, BO->getRHS(), MaxWidth);
5398
John McCall2ce81ad2010-01-06 22:07:33 +00005399 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005400 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005401 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005402 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005403 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005404
John McCall51431812011-07-14 22:39:48 +00005405 // The width of a division result is mostly determined by the size
5406 // of the LHS.
5407 case BO_Div: {
5408 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005409 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005410 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5411
5412 // If the divisor is constant, use that.
5413 llvm::APSInt divisor;
5414 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5415 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5416 if (log2 >= L.Width)
5417 L.Width = (L.NonNegative ? 0 : 1);
5418 else
5419 L.Width = std::min(L.Width - log2, MaxWidth);
5420 return L;
5421 }
5422
5423 // Otherwise, just use the LHS's width.
5424 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5425 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5426 }
5427
5428 // The result of a remainder can't be larger than the result of
5429 // either side.
5430 case BO_Rem: {
5431 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005432 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005433 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5434 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5435
5436 IntRange meet = IntRange::meet(L, R);
5437 meet.Width = std::min(meet.Width, MaxWidth);
5438 return meet;
5439 }
5440
5441 // The default behavior is okay for these.
5442 case BO_Mul:
5443 case BO_Add:
5444 case BO_Xor:
5445 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005446 break;
5447 }
5448
John McCall51431812011-07-14 22:39:48 +00005449 // The default case is to treat the operation as if it were closed
5450 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005451 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5452 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5453 return IntRange::join(L, R);
5454 }
5455
5456 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5457 switch (UO->getOpcode()) {
5458 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005459 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005460 return IntRange::forBoolType();
5461
5462 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005463 case UO_Deref:
5464 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005465 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005466
5467 default:
5468 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5469 }
5470 }
5471
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005472 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5473 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5474
John McCalld25db7e2013-05-06 21:39:12 +00005475 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005476 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005477 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005478
Eli Friedmane6d33952013-07-08 20:20:06 +00005479 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005480}
John McCall263a48b2010-01-04 23:31:57 +00005481
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005482static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005483 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005484}
5485
John McCall263a48b2010-01-04 23:31:57 +00005486/// Checks whether the given value, which currently has the given
5487/// source semantics, has the same value when coerced through the
5488/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005489static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5490 const llvm::fltSemantics &Src,
5491 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005492 llvm::APFloat truncated = value;
5493
5494 bool ignored;
5495 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5496 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5497
5498 return truncated.bitwiseIsEqual(value);
5499}
5500
5501/// Checks whether the given value, which currently has the given
5502/// source semantics, has the same value when coerced through the
5503/// target semantics.
5504///
5505/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005506static bool IsSameFloatAfterCast(const APValue &value,
5507 const llvm::fltSemantics &Src,
5508 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005509 if (value.isFloat())
5510 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5511
5512 if (value.isVector()) {
5513 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5514 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5515 return false;
5516 return true;
5517 }
5518
5519 assert(value.isComplexFloat());
5520 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5521 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5522}
5523
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005524static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005525
Ted Kremenek6274be42010-09-23 21:43:44 +00005526static bool IsZero(Sema &S, Expr *E) {
5527 // Suppress cases where we are comparing against an enum constant.
5528 if (const DeclRefExpr *DR =
5529 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5530 if (isa<EnumConstantDecl>(DR->getDecl()))
5531 return false;
5532
5533 // Suppress cases where the '0' value is expanded from a macro.
5534 if (E->getLocStart().isMacroID())
5535 return false;
5536
John McCallcc7e5bf2010-05-06 08:58:33 +00005537 llvm::APSInt Value;
5538 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5539}
5540
John McCall2551c1b2010-10-06 00:25:24 +00005541static bool HasEnumType(Expr *E) {
5542 // Strip off implicit integral promotions.
5543 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005544 if (ICE->getCastKind() != CK_IntegralCast &&
5545 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005546 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005547 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005548 }
5549
5550 return E->getType()->isEnumeralType();
5551}
5552
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005553static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005554 // Disable warning in template instantiations.
5555 if (!S.ActiveTemplateInstantiations.empty())
5556 return;
5557
John McCalle3027922010-08-25 11:45:40 +00005558 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005559 if (E->isValueDependent())
5560 return;
5561
John McCalle3027922010-08-25 11:45:40 +00005562 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005563 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005564 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005565 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005566 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005567 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005568 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005569 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005570 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005571 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005572 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005573 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005574 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005575 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005576 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005577 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5578 }
5579}
5580
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005581static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005582 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005583 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005584 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005585 // Disable warning in template instantiations.
5586 if (!S.ActiveTemplateInstantiations.empty())
5587 return;
5588
Richard Trieu0f097742014-04-04 04:13:47 +00005589 // TODO: Investigate using GetExprRange() to get tighter bounds
5590 // on the bit ranges.
5591 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005592 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5593 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005594 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5595 unsigned OtherWidth = OtherRange.Width;
5596
5597 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5598
Richard Trieu560910c2012-11-14 22:50:24 +00005599 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005600 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005601 return;
5602
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005603 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005604 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005605
Richard Trieu0f097742014-04-04 04:13:47 +00005606 // Used for diagnostic printout.
5607 enum {
5608 LiteralConstant = 0,
5609 CXXBoolLiteralTrue,
5610 CXXBoolLiteralFalse
5611 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005612
Richard Trieu0f097742014-04-04 04:13:47 +00005613 if (!OtherIsBooleanType) {
5614 QualType ConstantT = Constant->getType();
5615 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005616
Richard Trieu0f097742014-04-04 04:13:47 +00005617 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5618 return;
5619 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5620 "comparison with non-integer type");
5621
5622 bool ConstantSigned = ConstantT->isSignedIntegerType();
5623 bool CommonSigned = CommonT->isSignedIntegerType();
5624
5625 bool EqualityOnly = false;
5626
5627 if (CommonSigned) {
5628 // The common type is signed, therefore no signed to unsigned conversion.
5629 if (!OtherRange.NonNegative) {
5630 // Check that the constant is representable in type OtherT.
5631 if (ConstantSigned) {
5632 if (OtherWidth >= Value.getMinSignedBits())
5633 return;
5634 } else { // !ConstantSigned
5635 if (OtherWidth >= Value.getActiveBits() + 1)
5636 return;
5637 }
5638 } else { // !OtherSigned
5639 // Check that the constant is representable in type OtherT.
5640 // Negative values are out of range.
5641 if (ConstantSigned) {
5642 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5643 return;
5644 } else { // !ConstantSigned
5645 if (OtherWidth >= Value.getActiveBits())
5646 return;
5647 }
Richard Trieu560910c2012-11-14 22:50:24 +00005648 }
Richard Trieu0f097742014-04-04 04:13:47 +00005649 } else { // !CommonSigned
5650 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005651 if (OtherWidth >= Value.getActiveBits())
5652 return;
Craig Toppercf360162014-06-18 05:13:11 +00005653 } else { // OtherSigned
5654 assert(!ConstantSigned &&
5655 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005656 // Check to see if the constant is representable in OtherT.
5657 if (OtherWidth > Value.getActiveBits())
5658 return;
5659 // Check to see if the constant is equivalent to a negative value
5660 // cast to CommonT.
5661 if (S.Context.getIntWidth(ConstantT) ==
5662 S.Context.getIntWidth(CommonT) &&
5663 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5664 return;
5665 // The constant value rests between values that OtherT can represent
5666 // after conversion. Relational comparison still works, but equality
5667 // comparisons will be tautological.
5668 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005669 }
5670 }
Richard Trieu0f097742014-04-04 04:13:47 +00005671
5672 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5673
5674 if (op == BO_EQ || op == BO_NE) {
5675 IsTrue = op == BO_NE;
5676 } else if (EqualityOnly) {
5677 return;
5678 } else if (RhsConstant) {
5679 if (op == BO_GT || op == BO_GE)
5680 IsTrue = !PositiveConstant;
5681 else // op == BO_LT || op == BO_LE
5682 IsTrue = PositiveConstant;
5683 } else {
5684 if (op == BO_LT || op == BO_LE)
5685 IsTrue = !PositiveConstant;
5686 else // op == BO_GT || op == BO_GE
5687 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005688 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005689 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005690 // Other isKnownToHaveBooleanValue
5691 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5692 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5693 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5694
5695 static const struct LinkedConditions {
5696 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5697 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5698 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5699 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5700 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5701 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5702
5703 } TruthTable = {
5704 // Constant on LHS. | Constant on RHS. |
5705 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5706 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5707 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5708 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5709 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5710 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5711 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5712 };
5713
5714 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5715
5716 enum ConstantValue ConstVal = Zero;
5717 if (Value.isUnsigned() || Value.isNonNegative()) {
5718 if (Value == 0) {
5719 LiteralOrBoolConstant =
5720 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5721 ConstVal = Zero;
5722 } else if (Value == 1) {
5723 LiteralOrBoolConstant =
5724 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5725 ConstVal = One;
5726 } else {
5727 LiteralOrBoolConstant = LiteralConstant;
5728 ConstVal = GT_One;
5729 }
5730 } else {
5731 ConstVal = LT_Zero;
5732 }
5733
5734 CompareBoolWithConstantResult CmpRes;
5735
5736 switch (op) {
5737 case BO_LT:
5738 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5739 break;
5740 case BO_GT:
5741 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5742 break;
5743 case BO_LE:
5744 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5745 break;
5746 case BO_GE:
5747 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5748 break;
5749 case BO_EQ:
5750 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5751 break;
5752 case BO_NE:
5753 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5754 break;
5755 default:
5756 CmpRes = Unkwn;
5757 break;
5758 }
5759
5760 if (CmpRes == AFals) {
5761 IsTrue = false;
5762 } else if (CmpRes == ATrue) {
5763 IsTrue = true;
5764 } else {
5765 return;
5766 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005767 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005768
5769 // If this is a comparison to an enum constant, include that
5770 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005771 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005772 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5773 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5774
5775 SmallString<64> PrettySourceValue;
5776 llvm::raw_svector_ostream OS(PrettySourceValue);
5777 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005778 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005779 else
5780 OS << Value;
5781
Richard Trieu0f097742014-04-04 04:13:47 +00005782 S.DiagRuntimeBehavior(
5783 E->getOperatorLoc(), E,
5784 S.PDiag(diag::warn_out_of_range_compare)
5785 << OS.str() << LiteralOrBoolConstant
5786 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5787 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005788}
5789
John McCallcc7e5bf2010-05-06 08:58:33 +00005790/// Analyze the operands of the given comparison. Implements the
5791/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005792static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005793 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5794 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005795}
John McCall263a48b2010-01-04 23:31:57 +00005796
John McCallca01b222010-01-04 23:21:16 +00005797/// \brief Implements -Wsign-compare.
5798///
Richard Trieu82402a02011-09-15 21:56:47 +00005799/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005800static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005801 // The type the comparison is being performed in.
5802 QualType T = E->getLHS()->getType();
5803 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5804 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005805 if (E->isValueDependent())
5806 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005807
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005808 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5809 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005810
5811 bool IsComparisonConstant = false;
5812
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005813 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005814 // of 'true' or 'false'.
5815 if (T->isIntegralType(S.Context)) {
5816 llvm::APSInt RHSValue;
5817 bool IsRHSIntegralLiteral =
5818 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5819 llvm::APSInt LHSValue;
5820 bool IsLHSIntegralLiteral =
5821 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5822 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5823 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5824 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5825 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5826 else
5827 IsComparisonConstant =
5828 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005829 } else if (!T->hasUnsignedIntegerRepresentation())
5830 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005831
John McCallcc7e5bf2010-05-06 08:58:33 +00005832 // We don't do anything special if this isn't an unsigned integral
5833 // comparison: we're only interested in integral comparisons, and
5834 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005835 //
5836 // We also don't care about value-dependent expressions or expressions
5837 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005838 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005839 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005840
John McCallcc7e5bf2010-05-06 08:58:33 +00005841 // Check to see if one of the (unmodified) operands is of different
5842 // signedness.
5843 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005844 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5845 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005846 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005847 signedOperand = LHS;
5848 unsignedOperand = RHS;
5849 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5850 signedOperand = RHS;
5851 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005852 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005853 CheckTrivialUnsignedComparison(S, E);
5854 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005855 }
5856
John McCallcc7e5bf2010-05-06 08:58:33 +00005857 // Otherwise, calculate the effective range of the signed operand.
5858 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005859
John McCallcc7e5bf2010-05-06 08:58:33 +00005860 // Go ahead and analyze implicit conversions in the operands. Note
5861 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005862 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5863 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005864
John McCallcc7e5bf2010-05-06 08:58:33 +00005865 // If the signed range is non-negative, -Wsign-compare won't fire,
5866 // but we should still check for comparisons which are always true
5867 // or false.
5868 if (signedRange.NonNegative)
5869 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005870
5871 // For (in)equality comparisons, if the unsigned operand is a
5872 // constant which cannot collide with a overflowed signed operand,
5873 // then reinterpreting the signed operand as unsigned will not
5874 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005875 if (E->isEqualityOp()) {
5876 unsigned comparisonWidth = S.Context.getIntWidth(T);
5877 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005878
John McCallcc7e5bf2010-05-06 08:58:33 +00005879 // We should never be unable to prove that the unsigned operand is
5880 // non-negative.
5881 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5882
5883 if (unsignedRange.Width < comparisonWidth)
5884 return;
5885 }
5886
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005887 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5888 S.PDiag(diag::warn_mixed_sign_comparison)
5889 << LHS->getType() << RHS->getType()
5890 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005891}
5892
John McCall1f425642010-11-11 03:21:53 +00005893/// Analyzes an attempt to assign the given value to a bitfield.
5894///
5895/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005896static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5897 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005898 assert(Bitfield->isBitField());
5899 if (Bitfield->isInvalidDecl())
5900 return false;
5901
John McCalldeebbcf2010-11-11 05:33:51 +00005902 // White-list bool bitfields.
5903 if (Bitfield->getType()->isBooleanType())
5904 return false;
5905
Douglas Gregor789adec2011-02-04 13:09:01 +00005906 // Ignore value- or type-dependent expressions.
5907 if (Bitfield->getBitWidth()->isValueDependent() ||
5908 Bitfield->getBitWidth()->isTypeDependent() ||
5909 Init->isValueDependent() ||
5910 Init->isTypeDependent())
5911 return false;
5912
John McCall1f425642010-11-11 03:21:53 +00005913 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5914
Richard Smith5fab0c92011-12-28 19:48:30 +00005915 llvm::APSInt Value;
5916 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005917 return false;
5918
John McCall1f425642010-11-11 03:21:53 +00005919 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005920 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005921
5922 if (OriginalWidth <= FieldWidth)
5923 return false;
5924
Eli Friedmanc267a322012-01-26 23:11:39 +00005925 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005926 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005927 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005928
Eli Friedmanc267a322012-01-26 23:11:39 +00005929 // Check whether the stored value is equal to the original value.
5930 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005931 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005932 return false;
5933
Eli Friedmanc267a322012-01-26 23:11:39 +00005934 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005935 // therefore don't strictly fit into a signed bitfield of width 1.
5936 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005937 return false;
5938
John McCall1f425642010-11-11 03:21:53 +00005939 std::string PrettyValue = Value.toString(10);
5940 std::string PrettyTrunc = TruncatedValue.toString(10);
5941
5942 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5943 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5944 << Init->getSourceRange();
5945
5946 return true;
5947}
5948
John McCalld2a53122010-11-09 23:24:47 +00005949/// Analyze the given simple or compound assignment for warning-worthy
5950/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005951static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005952 // Just recurse on the LHS.
5953 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5954
5955 // We want to recurse on the RHS as normal unless we're assigning to
5956 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005957 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005958 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005959 E->getOperatorLoc())) {
5960 // Recurse, ignoring any implicit conversions on the RHS.
5961 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5962 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005963 }
5964 }
5965
5966 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5967}
5968
John McCall263a48b2010-01-04 23:31:57 +00005969/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005970static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005971 SourceLocation CContext, unsigned diag,
5972 bool pruneControlFlow = false) {
5973 if (pruneControlFlow) {
5974 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5975 S.PDiag(diag)
5976 << SourceType << T << E->getSourceRange()
5977 << SourceRange(CContext));
5978 return;
5979 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005980 S.Diag(E->getExprLoc(), diag)
5981 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5982}
5983
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005984/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005985static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005986 SourceLocation CContext, unsigned diag,
5987 bool pruneControlFlow = false) {
5988 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005989}
5990
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005991/// Diagnose an implicit cast from a literal expression. Does not warn when the
5992/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005993void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5994 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005995 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005996 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005997 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005998 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5999 T->hasUnsignedIntegerRepresentation());
6000 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006001 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006002 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006003 return;
6004
Eli Friedman07185912013-08-29 23:44:43 +00006005 // FIXME: Force the precision of the source value down so we don't print
6006 // digits which are usually useless (we don't really care here if we
6007 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6008 // would automatically print the shortest representation, but it's a bit
6009 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006010 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006011 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6012 precision = (precision * 59 + 195) / 196;
6013 Value.toString(PrettySourceValue, precision);
6014
David Blaikie9b88cc02012-05-15 17:18:27 +00006015 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006016 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6017 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6018 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006019 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006020
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006021 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006022 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6023 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006024}
6025
John McCall18a2c2c2010-11-09 22:22:12 +00006026std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6027 if (!Range.Width) return "0";
6028
6029 llvm::APSInt ValueInRange = Value;
6030 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006031 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006032 return ValueInRange.toString(10);
6033}
6034
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006035static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6036 if (!isa<ImplicitCastExpr>(Ex))
6037 return false;
6038
6039 Expr *InnerE = Ex->IgnoreParenImpCasts();
6040 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6041 const Type *Source =
6042 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6043 if (Target->isDependentType())
6044 return false;
6045
6046 const BuiltinType *FloatCandidateBT =
6047 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6048 const Type *BoolCandidateType = ToBool ? Target : Source;
6049
6050 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6051 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6052}
6053
6054void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6055 SourceLocation CC) {
6056 unsigned NumArgs = TheCall->getNumArgs();
6057 for (unsigned i = 0; i < NumArgs; ++i) {
6058 Expr *CurrA = TheCall->getArg(i);
6059 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6060 continue;
6061
6062 bool IsSwapped = ((i > 0) &&
6063 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6064 IsSwapped |= ((i < (NumArgs - 1)) &&
6065 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6066 if (IsSwapped) {
6067 // Warn on this floating-point to bool conversion.
6068 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6069 CurrA->getType(), CC,
6070 diag::warn_impcast_floating_point_to_bool);
6071 }
6072 }
6073}
6074
John McCallcc7e5bf2010-05-06 08:58:33 +00006075void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006076 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006077 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006078
John McCallcc7e5bf2010-05-06 08:58:33 +00006079 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6080 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6081 if (Source == Target) return;
6082 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006083
Chandler Carruthc22845a2011-07-26 05:40:03 +00006084 // If the conversion context location is invalid don't complain. We also
6085 // don't want to emit a warning if the issue occurs from the expansion of
6086 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6087 // delay this check as long as possible. Once we detect we are in that
6088 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006089 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006090 return;
6091
Richard Trieu021baa32011-09-23 20:10:00 +00006092 // Diagnose implicit casts to bool.
6093 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6094 if (isa<StringLiteral>(E))
6095 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006096 // and expressions, for instance, assert(0 && "error here"), are
6097 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006098 return DiagnoseImpCast(S, E, T, CC,
6099 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006100 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6101 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6102 // This covers the literal expressions that evaluate to Objective-C
6103 // objects.
6104 return DiagnoseImpCast(S, E, T, CC,
6105 diag::warn_impcast_objective_c_literal_to_bool);
6106 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006107 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6108 // Warn on pointer to bool conversion that is always true.
6109 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6110 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006111 }
Richard Trieu021baa32011-09-23 20:10:00 +00006112 }
John McCall263a48b2010-01-04 23:31:57 +00006113
6114 // Strip vector types.
6115 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006116 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006117 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006118 return;
John McCallacf0ee52010-10-08 02:01:28 +00006119 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006120 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006121
6122 // If the vector cast is cast between two vectors of the same size, it is
6123 // a bitcast, not a conversion.
6124 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6125 return;
John McCall263a48b2010-01-04 23:31:57 +00006126
6127 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6128 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6129 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006130 if (auto VecTy = dyn_cast<VectorType>(Target))
6131 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006132
6133 // Strip complex types.
6134 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006135 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006136 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006137 return;
6138
John McCallacf0ee52010-10-08 02:01:28 +00006139 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006140 }
John McCall263a48b2010-01-04 23:31:57 +00006141
6142 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6143 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6144 }
6145
6146 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6147 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6148
6149 // If the source is floating point...
6150 if (SourceBT && SourceBT->isFloatingPoint()) {
6151 // ...and the target is floating point...
6152 if (TargetBT && TargetBT->isFloatingPoint()) {
6153 // ...then warn if we're dropping FP rank.
6154
6155 // Builtin FP kinds are ordered by increasing FP rank.
6156 if (SourceBT->getKind() > TargetBT->getKind()) {
6157 // Don't warn about float constants that are precisely
6158 // representable in the target type.
6159 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006160 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006161 // Value might be a float, a float vector, or a float complex.
6162 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006163 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6164 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006165 return;
6166 }
6167
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006168 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006169 return;
6170
John McCallacf0ee52010-10-08 02:01:28 +00006171 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006172 }
6173 return;
6174 }
6175
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006176 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006177 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006178 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006179 return;
6180
Chandler Carruth22c7a792011-02-17 11:05:49 +00006181 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006182 // We also want to warn on, e.g., "int i = -1.234"
6183 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6184 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6185 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6186
Chandler Carruth016ef402011-04-10 08:36:24 +00006187 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6188 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006189 } else {
6190 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6191 }
6192 }
John McCall263a48b2010-01-04 23:31:57 +00006193
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006194 // If the target is bool, warn if expr is a function or method call.
6195 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6196 isa<CallExpr>(E)) {
6197 // Check last argument of function call to see if it is an
6198 // implicit cast from a type matching the type the result
6199 // is being cast to.
6200 CallExpr *CEx = cast<CallExpr>(E);
6201 unsigned NumArgs = CEx->getNumArgs();
6202 if (NumArgs > 0) {
6203 Expr *LastA = CEx->getArg(NumArgs - 1);
6204 Expr *InnerE = LastA->IgnoreParenImpCasts();
6205 const Type *InnerType =
6206 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6207 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6208 // Warn on this floating-point to bool conversion
6209 DiagnoseImpCast(S, E, T, CC,
6210 diag::warn_impcast_floating_point_to_bool);
6211 }
6212 }
6213 }
John McCall263a48b2010-01-04 23:31:57 +00006214 return;
6215 }
6216
Richard Trieubeaf3452011-05-29 19:59:02 +00006217 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006218 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006219 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006220 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006221 SourceLocation Loc = E->getSourceRange().getBegin();
6222 if (Loc.isMacroID())
6223 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006224 if (!Loc.isMacroID() || CC.isMacroID())
6225 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6226 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006227 << FixItHint::CreateReplacement(Loc,
6228 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006229 }
6230
David Blaikie9366d2b2012-06-19 21:19:06 +00006231 if (!Source->isIntegerType() || !Target->isIntegerType())
6232 return;
6233
David Blaikie7555b6a2012-05-15 16:56:36 +00006234 // TODO: remove this early return once the false positives for constant->bool
6235 // in templates, macros, etc, are reduced or removed.
6236 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6237 return;
6238
John McCallcc7e5bf2010-05-06 08:58:33 +00006239 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006240 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006241
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006242 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006243 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006244 // TODO: this should happen for bitfield stores, too.
6245 llvm::APSInt Value(32);
6246 if (E->isIntegerConstantExpr(Value, S.Context)) {
6247 if (S.SourceMgr.isInSystemMacro(CC))
6248 return;
6249
John McCall18a2c2c2010-11-09 22:22:12 +00006250 std::string PrettySourceValue = Value.toString(10);
6251 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006252
Ted Kremenek33ba9952011-10-22 02:37:33 +00006253 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6254 S.PDiag(diag::warn_impcast_integer_precision_constant)
6255 << PrettySourceValue << PrettyTargetValue
6256 << E->getType() << T << E->getSourceRange()
6257 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006258 return;
6259 }
6260
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006261 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6262 if (S.SourceMgr.isInSystemMacro(CC))
6263 return;
6264
David Blaikie9455da02012-04-12 22:40:54 +00006265 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006266 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6267 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006268 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006269 }
6270
6271 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6272 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6273 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006274
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006275 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006276 return;
6277
John McCallcc7e5bf2010-05-06 08:58:33 +00006278 unsigned DiagID = diag::warn_impcast_integer_sign;
6279
6280 // Traditionally, gcc has warned about this under -Wsign-compare.
6281 // We also want to warn about it in -Wconversion.
6282 // So if -Wconversion is off, use a completely identical diagnostic
6283 // in the sign-compare group.
6284 // The conditional-checking code will
6285 if (ICContext) {
6286 DiagID = diag::warn_impcast_integer_sign_conditional;
6287 *ICContext = true;
6288 }
6289
John McCallacf0ee52010-10-08 02:01:28 +00006290 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006291 }
6292
Douglas Gregora78f1932011-02-22 02:45:07 +00006293 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006294 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6295 // type, to give us better diagnostics.
6296 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006297 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006298 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6299 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6300 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6301 SourceType = S.Context.getTypeDeclType(Enum);
6302 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6303 }
6304 }
6305
Douglas Gregora78f1932011-02-22 02:45:07 +00006306 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6307 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006308 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6309 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006310 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006311 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006312 return;
6313
Douglas Gregor364f7db2011-03-12 00:14:31 +00006314 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006315 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006316 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006317
John McCall263a48b2010-01-04 23:31:57 +00006318 return;
6319}
6320
David Blaikie18e9ac72012-05-15 21:57:38 +00006321void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6322 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006323
6324void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006325 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006326 E = E->IgnoreParenImpCasts();
6327
6328 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006329 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006330
John McCallacf0ee52010-10-08 02:01:28 +00006331 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006332 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006333 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006334 return;
6335}
6336
David Blaikie18e9ac72012-05-15 21:57:38 +00006337void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6338 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006339 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006340
6341 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006342 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6343 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006344
6345 // If -Wconversion would have warned about either of the candidates
6346 // for a signedness conversion to the context type...
6347 if (!Suspicious) return;
6348
6349 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006350 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006351 return;
6352
John McCallcc7e5bf2010-05-06 08:58:33 +00006353 // ...then check whether it would have warned about either of the
6354 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006355 if (E->getType() == T) return;
6356
6357 Suspicious = false;
6358 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6359 E->getType(), CC, &Suspicious);
6360 if (!Suspicious)
6361 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006362 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006363}
6364
6365/// AnalyzeImplicitConversions - Find and report any interesting
6366/// implicit conversions in the given expression. There are a couple
6367/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006368void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006369 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006370 Expr *E = OrigE->IgnoreParenImpCasts();
6371
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006372 if (E->isTypeDependent() || E->isValueDependent())
6373 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006374
John McCallcc7e5bf2010-05-06 08:58:33 +00006375 // For conditional operators, we analyze the arguments as if they
6376 // were being fed directly into the output.
6377 if (isa<ConditionalOperator>(E)) {
6378 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006379 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006380 return;
6381 }
6382
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006383 // Check implicit argument conversions for function calls.
6384 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6385 CheckImplicitArgumentConversions(S, Call, CC);
6386
John McCallcc7e5bf2010-05-06 08:58:33 +00006387 // Go ahead and check any implicit conversions we might have skipped.
6388 // The non-canonical typecheck is just an optimization;
6389 // CheckImplicitConversion will filter out dead implicit conversions.
6390 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006391 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006392
6393 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006394
6395 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006396 if (POE->getResultExpr())
6397 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006398 }
6399
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006400 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6401 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6402
John McCallcc7e5bf2010-05-06 08:58:33 +00006403 // Skip past explicit casts.
6404 if (isa<ExplicitCastExpr>(E)) {
6405 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006406 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006407 }
6408
John McCalld2a53122010-11-09 23:24:47 +00006409 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6410 // Do a somewhat different check with comparison operators.
6411 if (BO->isComparisonOp())
6412 return AnalyzeComparison(S, BO);
6413
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006414 // And with simple assignments.
6415 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006416 return AnalyzeAssignment(S, BO);
6417 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006418
6419 // These break the otherwise-useful invariant below. Fortunately,
6420 // we don't really need to recurse into them, because any internal
6421 // expressions should have been analyzed already when they were
6422 // built into statements.
6423 if (isa<StmtExpr>(E)) return;
6424
6425 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006426 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006427
6428 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006429 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006430 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006431 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006432 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006433 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006434 if (!ChildExpr)
6435 continue;
6436
Richard Trieu955231d2014-01-25 01:10:35 +00006437 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006438 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006439 // Ignore checking string literals that are in logical and operators.
6440 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006441 continue;
6442 AnalyzeImplicitConversions(S, ChildExpr, CC);
6443 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006444}
6445
6446} // end anonymous namespace
6447
Richard Trieu3bb8b562014-02-26 02:36:06 +00006448enum {
6449 AddressOf,
6450 FunctionPointer,
6451 ArrayPointer
6452};
6453
Richard Trieuc1888e02014-06-28 23:25:37 +00006454// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6455// Returns true when emitting a warning about taking the address of a reference.
6456static bool CheckForReference(Sema &SemaRef, const Expr *E,
6457 PartialDiagnostic PD) {
6458 E = E->IgnoreParenImpCasts();
6459
6460 const FunctionDecl *FD = nullptr;
6461
6462 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6463 if (!DRE->getDecl()->getType()->isReferenceType())
6464 return false;
6465 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6466 if (!M->getMemberDecl()->getType()->isReferenceType())
6467 return false;
6468 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6469 if (!Call->getCallReturnType()->isReferenceType())
6470 return false;
6471 FD = Call->getDirectCallee();
6472 } else {
6473 return false;
6474 }
6475
6476 SemaRef.Diag(E->getExprLoc(), PD);
6477
6478 // If possible, point to location of function.
6479 if (FD) {
6480 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6481 }
6482
6483 return true;
6484}
6485
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006486// Returns true if the SourceLocation is expanded from any macro body.
6487// Returns false if the SourceLocation is invalid, is from not in a macro
6488// expansion, or is from expanded from a top-level macro argument.
6489static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6490 if (Loc.isInvalid())
6491 return false;
6492
6493 while (Loc.isMacroID()) {
6494 if (SM.isMacroBodyExpansion(Loc))
6495 return true;
6496 Loc = SM.getImmediateMacroCallerLoc(Loc);
6497 }
6498
6499 return false;
6500}
6501
Richard Trieu3bb8b562014-02-26 02:36:06 +00006502/// \brief Diagnose pointers that are always non-null.
6503/// \param E the expression containing the pointer
6504/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6505/// compared to a null pointer
6506/// \param IsEqual True when the comparison is equal to a null pointer
6507/// \param Range Extra SourceRange to highlight in the diagnostic
6508void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6509 Expr::NullPointerConstantKind NullKind,
6510 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006511 if (!E)
6512 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006513
6514 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006515 if (E->getExprLoc().isMacroID()) {
6516 const SourceManager &SM = getSourceManager();
6517 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6518 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006519 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006520 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006521 E = E->IgnoreImpCasts();
6522
6523 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6524
Richard Trieuf7432752014-06-06 21:39:26 +00006525 if (isa<CXXThisExpr>(E)) {
6526 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6527 : diag::warn_this_bool_conversion;
6528 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6529 return;
6530 }
6531
Richard Trieu3bb8b562014-02-26 02:36:06 +00006532 bool IsAddressOf = false;
6533
6534 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6535 if (UO->getOpcode() != UO_AddrOf)
6536 return;
6537 IsAddressOf = true;
6538 E = UO->getSubExpr();
6539 }
6540
Richard Trieuc1888e02014-06-28 23:25:37 +00006541 if (IsAddressOf) {
6542 unsigned DiagID = IsCompare
6543 ? diag::warn_address_of_reference_null_compare
6544 : diag::warn_address_of_reference_bool_conversion;
6545 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6546 << IsEqual;
6547 if (CheckForReference(*this, E, PD)) {
6548 return;
6549 }
6550 }
6551
Richard Trieu3bb8b562014-02-26 02:36:06 +00006552 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006553 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006554 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6555 D = R->getDecl();
6556 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6557 D = M->getMemberDecl();
6558 }
6559
6560 // Weak Decls can be null.
6561 if (!D || D->isWeak())
6562 return;
6563
6564 QualType T = D->getType();
6565 const bool IsArray = T->isArrayType();
6566 const bool IsFunction = T->isFunctionType();
6567
Richard Trieuc1888e02014-06-28 23:25:37 +00006568 // Address of function is used to silence the function warning.
6569 if (IsAddressOf && IsFunction) {
6570 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006571 }
6572
6573 // Found nothing.
6574 if (!IsAddressOf && !IsFunction && !IsArray)
6575 return;
6576
6577 // Pretty print the expression for the diagnostic.
6578 std::string Str;
6579 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006580 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006581
6582 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6583 : diag::warn_impcast_pointer_to_bool;
6584 unsigned DiagType;
6585 if (IsAddressOf)
6586 DiagType = AddressOf;
6587 else if (IsFunction)
6588 DiagType = FunctionPointer;
6589 else if (IsArray)
6590 DiagType = ArrayPointer;
6591 else
6592 llvm_unreachable("Could not determine diagnostic.");
6593 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6594 << Range << IsEqual;
6595
6596 if (!IsFunction)
6597 return;
6598
6599 // Suggest '&' to silence the function warning.
6600 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6601 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6602
6603 // Check to see if '()' fixit should be emitted.
6604 QualType ReturnType;
6605 UnresolvedSet<4> NonTemplateOverloads;
6606 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6607 if (ReturnType.isNull())
6608 return;
6609
6610 if (IsCompare) {
6611 // There are two cases here. If there is null constant, the only suggest
6612 // for a pointer return type. If the null is 0, then suggest if the return
6613 // type is a pointer or an integer type.
6614 if (!ReturnType->isPointerType()) {
6615 if (NullKind == Expr::NPCK_ZeroExpression ||
6616 NullKind == Expr::NPCK_ZeroLiteral) {
6617 if (!ReturnType->isIntegerType())
6618 return;
6619 } else {
6620 return;
6621 }
6622 }
6623 } else { // !IsCompare
6624 // For function to bool, only suggest if the function pointer has bool
6625 // return type.
6626 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6627 return;
6628 }
6629 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006630 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006631}
6632
6633
John McCallcc7e5bf2010-05-06 08:58:33 +00006634/// Diagnoses "dangerous" implicit conversions within the given
6635/// expression (which is a full expression). Implements -Wconversion
6636/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006637///
6638/// \param CC the "context" location of the implicit conversion, i.e.
6639/// the most location of the syntactic entity requiring the implicit
6640/// conversion
6641void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006642 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006643 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006644 return;
6645
6646 // Don't diagnose for value- or type-dependent expressions.
6647 if (E->isTypeDependent() || E->isValueDependent())
6648 return;
6649
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006650 // Check for array bounds violations in cases where the check isn't triggered
6651 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6652 // ArraySubscriptExpr is on the RHS of a variable initialization.
6653 CheckArrayAccess(E);
6654
John McCallacf0ee52010-10-08 02:01:28 +00006655 // This is not the right CC for (e.g.) a variable initialization.
6656 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006657}
6658
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006659/// Diagnose when expression is an integer constant expression and its evaluation
6660/// results in integer overflow
6661void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006662 if (isa<BinaryOperator>(E->IgnoreParens()))
6663 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006664}
6665
Richard Smithc406cb72013-01-17 01:17:56 +00006666namespace {
6667/// \brief Visitor for expressions which looks for unsequenced operations on the
6668/// same object.
6669class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006670 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6671
Richard Smithc406cb72013-01-17 01:17:56 +00006672 /// \brief A tree of sequenced regions within an expression. Two regions are
6673 /// unsequenced if one is an ancestor or a descendent of the other. When we
6674 /// finish processing an expression with sequencing, such as a comma
6675 /// expression, we fold its tree nodes into its parent, since they are
6676 /// unsequenced with respect to nodes we will visit later.
6677 class SequenceTree {
6678 struct Value {
6679 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6680 unsigned Parent : 31;
6681 bool Merged : 1;
6682 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006683 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006684
6685 public:
6686 /// \brief A region within an expression which may be sequenced with respect
6687 /// to some other region.
6688 class Seq {
6689 explicit Seq(unsigned N) : Index(N) {}
6690 unsigned Index;
6691 friend class SequenceTree;
6692 public:
6693 Seq() : Index(0) {}
6694 };
6695
6696 SequenceTree() { Values.push_back(Value(0)); }
6697 Seq root() const { return Seq(0); }
6698
6699 /// \brief Create a new sequence of operations, which is an unsequenced
6700 /// subset of \p Parent. This sequence of operations is sequenced with
6701 /// respect to other children of \p Parent.
6702 Seq allocate(Seq Parent) {
6703 Values.push_back(Value(Parent.Index));
6704 return Seq(Values.size() - 1);
6705 }
6706
6707 /// \brief Merge a sequence of operations into its parent.
6708 void merge(Seq S) {
6709 Values[S.Index].Merged = true;
6710 }
6711
6712 /// \brief Determine whether two operations are unsequenced. This operation
6713 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6714 /// should have been merged into its parent as appropriate.
6715 bool isUnsequenced(Seq Cur, Seq Old) {
6716 unsigned C = representative(Cur.Index);
6717 unsigned Target = representative(Old.Index);
6718 while (C >= Target) {
6719 if (C == Target)
6720 return true;
6721 C = Values[C].Parent;
6722 }
6723 return false;
6724 }
6725
6726 private:
6727 /// \brief Pick a representative for a sequence.
6728 unsigned representative(unsigned K) {
6729 if (Values[K].Merged)
6730 // Perform path compression as we go.
6731 return Values[K].Parent = representative(Values[K].Parent);
6732 return K;
6733 }
6734 };
6735
6736 /// An object for which we can track unsequenced uses.
6737 typedef NamedDecl *Object;
6738
6739 /// Different flavors of object usage which we track. We only track the
6740 /// least-sequenced usage of each kind.
6741 enum UsageKind {
6742 /// A read of an object. Multiple unsequenced reads are OK.
6743 UK_Use,
6744 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006745 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006746 UK_ModAsValue,
6747 /// A modification of an object which is not sequenced before the value
6748 /// computation of the expression, such as n++.
6749 UK_ModAsSideEffect,
6750
6751 UK_Count = UK_ModAsSideEffect + 1
6752 };
6753
6754 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006755 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006756 Expr *Use;
6757 SequenceTree::Seq Seq;
6758 };
6759
6760 struct UsageInfo {
6761 UsageInfo() : Diagnosed(false) {}
6762 Usage Uses[UK_Count];
6763 /// Have we issued a diagnostic for this variable already?
6764 bool Diagnosed;
6765 };
6766 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6767
6768 Sema &SemaRef;
6769 /// Sequenced regions within the expression.
6770 SequenceTree Tree;
6771 /// Declaration modifications and references which we have seen.
6772 UsageInfoMap UsageMap;
6773 /// The region we are currently within.
6774 SequenceTree::Seq Region;
6775 /// Filled in with declarations which were modified as a side-effect
6776 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006777 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006778 /// Expressions to check later. We defer checking these to reduce
6779 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006780 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006781
6782 /// RAII object wrapping the visitation of a sequenced subexpression of an
6783 /// expression. At the end of this process, the side-effects of the evaluation
6784 /// become sequenced with respect to the value computation of the result, so
6785 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6786 /// UK_ModAsValue.
6787 struct SequencedSubexpression {
6788 SequencedSubexpression(SequenceChecker &Self)
6789 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6790 Self.ModAsSideEffect = &ModAsSideEffect;
6791 }
6792 ~SequencedSubexpression() {
6793 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6794 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6795 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6796 Self.addUsage(U, ModAsSideEffect[I].first,
6797 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6798 }
6799 Self.ModAsSideEffect = OldModAsSideEffect;
6800 }
6801
6802 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006803 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6804 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006805 };
6806
Richard Smith40238f02013-06-20 22:21:56 +00006807 /// RAII object wrapping the visitation of a subexpression which we might
6808 /// choose to evaluate as a constant. If any subexpression is evaluated and
6809 /// found to be non-constant, this allows us to suppress the evaluation of
6810 /// the outer expression.
6811 class EvaluationTracker {
6812 public:
6813 EvaluationTracker(SequenceChecker &Self)
6814 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6815 Self.EvalTracker = this;
6816 }
6817 ~EvaluationTracker() {
6818 Self.EvalTracker = Prev;
6819 if (Prev)
6820 Prev->EvalOK &= EvalOK;
6821 }
6822
6823 bool evaluate(const Expr *E, bool &Result) {
6824 if (!EvalOK || E->isValueDependent())
6825 return false;
6826 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6827 return EvalOK;
6828 }
6829
6830 private:
6831 SequenceChecker &Self;
6832 EvaluationTracker *Prev;
6833 bool EvalOK;
6834 } *EvalTracker;
6835
Richard Smithc406cb72013-01-17 01:17:56 +00006836 /// \brief Find the object which is produced by the specified expression,
6837 /// if any.
6838 Object getObject(Expr *E, bool Mod) const {
6839 E = E->IgnoreParenCasts();
6840 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6841 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6842 return getObject(UO->getSubExpr(), Mod);
6843 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6844 if (BO->getOpcode() == BO_Comma)
6845 return getObject(BO->getRHS(), Mod);
6846 if (Mod && BO->isAssignmentOp())
6847 return getObject(BO->getLHS(), Mod);
6848 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6849 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6850 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6851 return ME->getMemberDecl();
6852 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6853 // FIXME: If this is a reference, map through to its value.
6854 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006855 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006856 }
6857
6858 /// \brief Note that an object was modified or used by an expression.
6859 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6860 Usage &U = UI.Uses[UK];
6861 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6862 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6863 ModAsSideEffect->push_back(std::make_pair(O, U));
6864 U.Use = Ref;
6865 U.Seq = Region;
6866 }
6867 }
6868 /// \brief Check whether a modification or use conflicts with a prior usage.
6869 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6870 bool IsModMod) {
6871 if (UI.Diagnosed)
6872 return;
6873
6874 const Usage &U = UI.Uses[OtherKind];
6875 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6876 return;
6877
6878 Expr *Mod = U.Use;
6879 Expr *ModOrUse = Ref;
6880 if (OtherKind == UK_Use)
6881 std::swap(Mod, ModOrUse);
6882
6883 SemaRef.Diag(Mod->getExprLoc(),
6884 IsModMod ? diag::warn_unsequenced_mod_mod
6885 : diag::warn_unsequenced_mod_use)
6886 << O << SourceRange(ModOrUse->getExprLoc());
6887 UI.Diagnosed = true;
6888 }
6889
6890 void notePreUse(Object O, Expr *Use) {
6891 UsageInfo &U = UsageMap[O];
6892 // Uses conflict with other modifications.
6893 checkUsage(O, U, Use, UK_ModAsValue, false);
6894 }
6895 void notePostUse(Object O, Expr *Use) {
6896 UsageInfo &U = UsageMap[O];
6897 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6898 addUsage(U, O, Use, UK_Use);
6899 }
6900
6901 void notePreMod(Object O, Expr *Mod) {
6902 UsageInfo &U = UsageMap[O];
6903 // Modifications conflict with other modifications and with uses.
6904 checkUsage(O, U, Mod, UK_ModAsValue, true);
6905 checkUsage(O, U, Mod, UK_Use, false);
6906 }
6907 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6908 UsageInfo &U = UsageMap[O];
6909 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6910 addUsage(U, O, Use, UK);
6911 }
6912
6913public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006914 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006915 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6916 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006917 Visit(E);
6918 }
6919
6920 void VisitStmt(Stmt *S) {
6921 // Skip all statements which aren't expressions for now.
6922 }
6923
6924 void VisitExpr(Expr *E) {
6925 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006926 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006927 }
6928
6929 void VisitCastExpr(CastExpr *E) {
6930 Object O = Object();
6931 if (E->getCastKind() == CK_LValueToRValue)
6932 O = getObject(E->getSubExpr(), false);
6933
6934 if (O)
6935 notePreUse(O, E);
6936 VisitExpr(E);
6937 if (O)
6938 notePostUse(O, E);
6939 }
6940
6941 void VisitBinComma(BinaryOperator *BO) {
6942 // C++11 [expr.comma]p1:
6943 // Every value computation and side effect associated with the left
6944 // expression is sequenced before every value computation and side
6945 // effect associated with the right expression.
6946 SequenceTree::Seq LHS = Tree.allocate(Region);
6947 SequenceTree::Seq RHS = Tree.allocate(Region);
6948 SequenceTree::Seq OldRegion = Region;
6949
6950 {
6951 SequencedSubexpression SeqLHS(*this);
6952 Region = LHS;
6953 Visit(BO->getLHS());
6954 }
6955
6956 Region = RHS;
6957 Visit(BO->getRHS());
6958
6959 Region = OldRegion;
6960
6961 // Forget that LHS and RHS are sequenced. They are both unsequenced
6962 // with respect to other stuff.
6963 Tree.merge(LHS);
6964 Tree.merge(RHS);
6965 }
6966
6967 void VisitBinAssign(BinaryOperator *BO) {
6968 // The modification is sequenced after the value computation of the LHS
6969 // and RHS, so check it before inspecting the operands and update the
6970 // map afterwards.
6971 Object O = getObject(BO->getLHS(), true);
6972 if (!O)
6973 return VisitExpr(BO);
6974
6975 notePreMod(O, BO);
6976
6977 // C++11 [expr.ass]p7:
6978 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6979 // only once.
6980 //
6981 // Therefore, for a compound assignment operator, O is considered used
6982 // everywhere except within the evaluation of E1 itself.
6983 if (isa<CompoundAssignOperator>(BO))
6984 notePreUse(O, BO);
6985
6986 Visit(BO->getLHS());
6987
6988 if (isa<CompoundAssignOperator>(BO))
6989 notePostUse(O, BO);
6990
6991 Visit(BO->getRHS());
6992
Richard Smith83e37bee2013-06-26 23:16:51 +00006993 // C++11 [expr.ass]p1:
6994 // the assignment is sequenced [...] before the value computation of the
6995 // assignment expression.
6996 // C11 6.5.16/3 has no such rule.
6997 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6998 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006999 }
7000 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7001 VisitBinAssign(CAO);
7002 }
7003
7004 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7005 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7006 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7007 Object O = getObject(UO->getSubExpr(), true);
7008 if (!O)
7009 return VisitExpr(UO);
7010
7011 notePreMod(O, UO);
7012 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007013 // C++11 [expr.pre.incr]p1:
7014 // the expression ++x is equivalent to x+=1
7015 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7016 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007017 }
7018
7019 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7020 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7021 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7022 Object O = getObject(UO->getSubExpr(), true);
7023 if (!O)
7024 return VisitExpr(UO);
7025
7026 notePreMod(O, UO);
7027 Visit(UO->getSubExpr());
7028 notePostMod(O, UO, UK_ModAsSideEffect);
7029 }
7030
7031 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7032 void VisitBinLOr(BinaryOperator *BO) {
7033 // The side-effects of the LHS of an '&&' are sequenced before the
7034 // value computation of the RHS, and hence before the value computation
7035 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7036 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007037 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007038 {
7039 SequencedSubexpression Sequenced(*this);
7040 Visit(BO->getLHS());
7041 }
7042
7043 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007044 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007045 if (!Result)
7046 Visit(BO->getRHS());
7047 } else {
7048 // Check for unsequenced operations in the RHS, treating it as an
7049 // entirely separate evaluation.
7050 //
7051 // FIXME: If there are operations in the RHS which are unsequenced
7052 // with respect to operations outside the RHS, and those operations
7053 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007054 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007055 }
Richard Smithc406cb72013-01-17 01:17:56 +00007056 }
7057 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007058 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007059 {
7060 SequencedSubexpression Sequenced(*this);
7061 Visit(BO->getLHS());
7062 }
7063
7064 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007065 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007066 if (Result)
7067 Visit(BO->getRHS());
7068 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007069 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007070 }
Richard Smithc406cb72013-01-17 01:17:56 +00007071 }
7072
7073 // Only visit the condition, unless we can be sure which subexpression will
7074 // be chosen.
7075 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007076 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007077 {
7078 SequencedSubexpression Sequenced(*this);
7079 Visit(CO->getCond());
7080 }
Richard Smithc406cb72013-01-17 01:17:56 +00007081
7082 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007083 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007084 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007085 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007086 WorkList.push_back(CO->getTrueExpr());
7087 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007088 }
Richard Smithc406cb72013-01-17 01:17:56 +00007089 }
7090
Richard Smithe3dbfe02013-06-30 10:40:20 +00007091 void VisitCallExpr(CallExpr *CE) {
7092 // C++11 [intro.execution]p15:
7093 // When calling a function [...], every value computation and side effect
7094 // associated with any argument expression, or with the postfix expression
7095 // designating the called function, is sequenced before execution of every
7096 // expression or statement in the body of the function [and thus before
7097 // the value computation of its result].
7098 SequencedSubexpression Sequenced(*this);
7099 Base::VisitCallExpr(CE);
7100
7101 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7102 }
7103
Richard Smithc406cb72013-01-17 01:17:56 +00007104 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007105 // This is a call, so all subexpressions are sequenced before the result.
7106 SequencedSubexpression Sequenced(*this);
7107
Richard Smithc406cb72013-01-17 01:17:56 +00007108 if (!CCE->isListInitialization())
7109 return VisitExpr(CCE);
7110
7111 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007112 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007113 SequenceTree::Seq Parent = Region;
7114 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7115 E = CCE->arg_end();
7116 I != E; ++I) {
7117 Region = Tree.allocate(Parent);
7118 Elts.push_back(Region);
7119 Visit(*I);
7120 }
7121
7122 // Forget that the initializers are sequenced.
7123 Region = Parent;
7124 for (unsigned I = 0; I < Elts.size(); ++I)
7125 Tree.merge(Elts[I]);
7126 }
7127
7128 void VisitInitListExpr(InitListExpr *ILE) {
7129 if (!SemaRef.getLangOpts().CPlusPlus11)
7130 return VisitExpr(ILE);
7131
7132 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007133 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007134 SequenceTree::Seq Parent = Region;
7135 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7136 Expr *E = ILE->getInit(I);
7137 if (!E) continue;
7138 Region = Tree.allocate(Parent);
7139 Elts.push_back(Region);
7140 Visit(E);
7141 }
7142
7143 // Forget that the initializers are sequenced.
7144 Region = Parent;
7145 for (unsigned I = 0; I < Elts.size(); ++I)
7146 Tree.merge(Elts[I]);
7147 }
7148};
7149}
7150
7151void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007152 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007153 WorkList.push_back(E);
7154 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007155 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007156 SequenceChecker(*this, Item, WorkList);
7157 }
Richard Smithc406cb72013-01-17 01:17:56 +00007158}
7159
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007160void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7161 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007162 CheckImplicitConversions(E, CheckLoc);
7163 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007164 if (!IsConstexpr && !E->isValueDependent())
7165 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007166}
7167
John McCall1f425642010-11-11 03:21:53 +00007168void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7169 FieldDecl *BitField,
7170 Expr *Init) {
7171 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7172}
7173
Mike Stump0c2ec772010-01-21 03:59:47 +00007174/// CheckParmsForFunctionDef - Check that the parameters of the given
7175/// function are appropriate for the definition of a function. This
7176/// takes care of any checks that cannot be performed on the
7177/// declaration itself, e.g., that the types of each of the function
7178/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007179bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7180 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007181 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007182 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007183 for (; P != PEnd; ++P) {
7184 ParmVarDecl *Param = *P;
7185
Mike Stump0c2ec772010-01-21 03:59:47 +00007186 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7187 // function declarator that is part of a function definition of
7188 // that function shall not have incomplete type.
7189 //
7190 // This is also C++ [dcl.fct]p6.
7191 if (!Param->isInvalidDecl() &&
7192 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007193 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007194 Param->setInvalidDecl();
7195 HasInvalidParm = true;
7196 }
7197
7198 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7199 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007200 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007201 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007202 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007203 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007204 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007205
7206 // C99 6.7.5.3p12:
7207 // If the function declarator is not part of a definition of that
7208 // function, parameters may have incomplete type and may use the [*]
7209 // notation in their sequences of declarator specifiers to specify
7210 // variable length array types.
7211 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007212 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007213 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007214 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007215 // information is added for it.
7216 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007217 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007218 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007219 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007220 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007221
7222 // MSVC destroys objects passed by value in the callee. Therefore a
7223 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007224 // object's destructor. However, we don't perform any direct access check
7225 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007226 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7227 .getCXXABI()
7228 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007229 if (!Param->isInvalidDecl()) {
7230 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7231 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7232 if (!ClassDecl->isInvalidDecl() &&
7233 !ClassDecl->hasIrrelevantDestructor() &&
7234 !ClassDecl->isDependentContext()) {
7235 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7236 MarkFunctionReferenced(Param->getLocation(), Destructor);
7237 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7238 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007239 }
7240 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007241 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007242 }
7243
7244 return HasInvalidParm;
7245}
John McCall2b5c1b22010-08-12 21:44:57 +00007246
7247/// CheckCastAlign - Implements -Wcast-align, which warns when a
7248/// pointer cast increases the alignment requirements.
7249void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7250 // This is actually a lot of work to potentially be doing on every
7251 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007252 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007253 return;
7254
7255 // Ignore dependent types.
7256 if (T->isDependentType() || Op->getType()->isDependentType())
7257 return;
7258
7259 // Require that the destination be a pointer type.
7260 const PointerType *DestPtr = T->getAs<PointerType>();
7261 if (!DestPtr) return;
7262
7263 // If the destination has alignment 1, we're done.
7264 QualType DestPointee = DestPtr->getPointeeType();
7265 if (DestPointee->isIncompleteType()) return;
7266 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7267 if (DestAlign.isOne()) return;
7268
7269 // Require that the source be a pointer type.
7270 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7271 if (!SrcPtr) return;
7272 QualType SrcPointee = SrcPtr->getPointeeType();
7273
7274 // Whitelist casts from cv void*. We already implicitly
7275 // whitelisted casts to cv void*, since they have alignment 1.
7276 // Also whitelist casts involving incomplete types, which implicitly
7277 // includes 'void'.
7278 if (SrcPointee->isIncompleteType()) return;
7279
7280 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7281 if (SrcAlign >= DestAlign) return;
7282
7283 Diag(TRange.getBegin(), diag::warn_cast_align)
7284 << Op->getType() << T
7285 << static_cast<unsigned>(SrcAlign.getQuantity())
7286 << static_cast<unsigned>(DestAlign.getQuantity())
7287 << TRange << Op->getSourceRange();
7288}
7289
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007290static const Type* getElementType(const Expr *BaseExpr) {
7291 const Type* EltType = BaseExpr->getType().getTypePtr();
7292 if (EltType->isAnyPointerType())
7293 return EltType->getPointeeType().getTypePtr();
7294 else if (EltType->isArrayType())
7295 return EltType->getBaseElementTypeUnsafe();
7296 return EltType;
7297}
7298
Chandler Carruth28389f02011-08-05 09:10:50 +00007299/// \brief Check whether this array fits the idiom of a size-one tail padded
7300/// array member of a struct.
7301///
7302/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7303/// commonly used to emulate flexible arrays in C89 code.
7304static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7305 const NamedDecl *ND) {
7306 if (Size != 1 || !ND) return false;
7307
7308 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7309 if (!FD) return false;
7310
7311 // Don't consider sizes resulting from macro expansions or template argument
7312 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007313
7314 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007315 while (TInfo) {
7316 TypeLoc TL = TInfo->getTypeLoc();
7317 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007318 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7319 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007320 TInfo = TDL->getTypeSourceInfo();
7321 continue;
7322 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007323 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7324 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007325 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7326 return false;
7327 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007328 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007329 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007330
7331 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007332 if (!RD) return false;
7333 if (RD->isUnion()) return false;
7334 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7335 if (!CRD->isStandardLayout()) return false;
7336 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007337
Benjamin Kramer8c543672011-08-06 03:04:42 +00007338 // See if this is the last field decl in the record.
7339 const Decl *D = FD;
7340 while ((D = D->getNextDeclInContext()))
7341 if (isa<FieldDecl>(D))
7342 return false;
7343 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007344}
7345
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007346void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007347 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007348 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007349 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007350 if (IndexExpr->isValueDependent())
7351 return;
7352
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007353 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007354 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007355 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007356 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007357 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007358 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007359
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007360 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007361 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007362 return;
Richard Smith13f67182011-12-16 19:31:14 +00007363 if (IndexNegated)
7364 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007365
Craig Topperc3ec1492014-05-26 06:22:03 +00007366 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007367 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7368 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007369 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007370 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007371
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007372 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007373 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007374 if (!size.isStrictlyPositive())
7375 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007376
7377 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007378 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007379 // Make sure we're comparing apples to apples when comparing index to size
7380 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7381 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007382 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007383 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007384 if (ptrarith_typesize != array_typesize) {
7385 // There's a cast to a different size type involved
7386 uint64_t ratio = array_typesize / ptrarith_typesize;
7387 // TODO: Be smarter about handling cases where array_typesize is not a
7388 // multiple of ptrarith_typesize
7389 if (ptrarith_typesize * ratio == array_typesize)
7390 size *= llvm::APInt(size.getBitWidth(), ratio);
7391 }
7392 }
7393
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007394 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007395 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007396 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007397 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007398
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007399 // For array subscripting the index must be less than size, but for pointer
7400 // arithmetic also allow the index (offset) to be equal to size since
7401 // computing the next address after the end of the array is legal and
7402 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007403 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007404 return;
7405
7406 // Also don't warn for arrays of size 1 which are members of some
7407 // structure. These are often used to approximate flexible arrays in C89
7408 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007409 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007410 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007411
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007412 // Suppress the warning if the subscript expression (as identified by the
7413 // ']' location) and the index expression are both from macro expansions
7414 // within a system header.
7415 if (ASE) {
7416 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7417 ASE->getRBracketLoc());
7418 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7419 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7420 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007421 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007422 return;
7423 }
7424 }
7425
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007426 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007427 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007428 DiagID = diag::warn_array_index_exceeds_bounds;
7429
7430 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7431 PDiag(DiagID) << index.toString(10, true)
7432 << size.toString(10, true)
7433 << (unsigned)size.getLimitedValue(~0U)
7434 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007435 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007436 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007437 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007438 DiagID = diag::warn_ptr_arith_precedes_bounds;
7439 if (index.isNegative()) index = -index;
7440 }
7441
7442 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7443 PDiag(DiagID) << index.toString(10, true)
7444 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007445 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007446
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007447 if (!ND) {
7448 // Try harder to find a NamedDecl to point at in the note.
7449 while (const ArraySubscriptExpr *ASE =
7450 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7451 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7453 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7454 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7455 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7456 }
7457
Chandler Carruth1af88f12011-02-17 21:10:52 +00007458 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007459 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7460 PDiag(diag::note_array_index_out_of_bounds)
7461 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007462}
7463
Ted Kremenekdf26df72011-03-01 18:41:00 +00007464void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007465 int AllowOnePastEnd = 0;
7466 while (expr) {
7467 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007468 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007469 case Stmt::ArraySubscriptExprClass: {
7470 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007471 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007472 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007473 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007474 }
7475 case Stmt::UnaryOperatorClass: {
7476 // Only unwrap the * and & unary operators
7477 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7478 expr = UO->getSubExpr();
7479 switch (UO->getOpcode()) {
7480 case UO_AddrOf:
7481 AllowOnePastEnd++;
7482 break;
7483 case UO_Deref:
7484 AllowOnePastEnd--;
7485 break;
7486 default:
7487 return;
7488 }
7489 break;
7490 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007491 case Stmt::ConditionalOperatorClass: {
7492 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7493 if (const Expr *lhs = cond->getLHS())
7494 CheckArrayAccess(lhs);
7495 if (const Expr *rhs = cond->getRHS())
7496 CheckArrayAccess(rhs);
7497 return;
7498 }
7499 default:
7500 return;
7501 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007502 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007503}
John McCall31168b02011-06-15 23:02:42 +00007504
7505//===--- CHECK: Objective-C retain cycles ----------------------------------//
7506
7507namespace {
7508 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007509 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007510 VarDecl *Variable;
7511 SourceRange Range;
7512 SourceLocation Loc;
7513 bool Indirect;
7514
7515 void setLocsFrom(Expr *e) {
7516 Loc = e->getExprLoc();
7517 Range = e->getSourceRange();
7518 }
7519 };
7520}
7521
7522/// Consider whether capturing the given variable can possibly lead to
7523/// a retain cycle.
7524static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007525 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007526 // lifetime. In MRR, it's captured strongly if the variable is
7527 // __block and has an appropriate type.
7528 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7529 return false;
7530
7531 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007532 if (ref)
7533 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007534 return true;
7535}
7536
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007537static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007538 while (true) {
7539 e = e->IgnoreParens();
7540 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7541 switch (cast->getCastKind()) {
7542 case CK_BitCast:
7543 case CK_LValueBitCast:
7544 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007545 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007546 e = cast->getSubExpr();
7547 continue;
7548
John McCall31168b02011-06-15 23:02:42 +00007549 default:
7550 return false;
7551 }
7552 }
7553
7554 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7555 ObjCIvarDecl *ivar = ref->getDecl();
7556 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7557 return false;
7558
7559 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007560 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007561 return false;
7562
7563 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7564 owner.Indirect = true;
7565 return true;
7566 }
7567
7568 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7569 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7570 if (!var) return false;
7571 return considerVariable(var, ref, owner);
7572 }
7573
John McCall31168b02011-06-15 23:02:42 +00007574 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7575 if (member->isArrow()) return false;
7576
7577 // Don't count this as an indirect ownership.
7578 e = member->getBase();
7579 continue;
7580 }
7581
John McCallfe96e0b2011-11-06 09:01:30 +00007582 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7583 // Only pay attention to pseudo-objects on property references.
7584 ObjCPropertyRefExpr *pre
7585 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7586 ->IgnoreParens());
7587 if (!pre) return false;
7588 if (pre->isImplicitProperty()) return false;
7589 ObjCPropertyDecl *property = pre->getExplicitProperty();
7590 if (!property->isRetaining() &&
7591 !(property->getPropertyIvarDecl() &&
7592 property->getPropertyIvarDecl()->getType()
7593 .getObjCLifetime() == Qualifiers::OCL_Strong))
7594 return false;
7595
7596 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007597 if (pre->isSuperReceiver()) {
7598 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7599 if (!owner.Variable)
7600 return false;
7601 owner.Loc = pre->getLocation();
7602 owner.Range = pre->getSourceRange();
7603 return true;
7604 }
John McCallfe96e0b2011-11-06 09:01:30 +00007605 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7606 ->getSourceExpr());
7607 continue;
7608 }
7609
John McCall31168b02011-06-15 23:02:42 +00007610 // Array ivars?
7611
7612 return false;
7613 }
7614}
7615
7616namespace {
7617 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7618 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7619 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007620 Context(Context), Variable(variable), Capturer(nullptr),
7621 VarWillBeReased(false) {}
7622 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007623 VarDecl *Variable;
7624 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007625 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007626
7627 void VisitDeclRefExpr(DeclRefExpr *ref) {
7628 if (ref->getDecl() == Variable && !Capturer)
7629 Capturer = ref;
7630 }
7631
John McCall31168b02011-06-15 23:02:42 +00007632 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7633 if (Capturer) return;
7634 Visit(ref->getBase());
7635 if (Capturer && ref->isFreeIvar())
7636 Capturer = ref;
7637 }
7638
7639 void VisitBlockExpr(BlockExpr *block) {
7640 // Look inside nested blocks
7641 if (block->getBlockDecl()->capturesVariable(Variable))
7642 Visit(block->getBlockDecl()->getBody());
7643 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007644
7645 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7646 if (Capturer) return;
7647 if (OVE->getSourceExpr())
7648 Visit(OVE->getSourceExpr());
7649 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007650 void VisitBinaryOperator(BinaryOperator *BinOp) {
7651 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7652 return;
7653 Expr *LHS = BinOp->getLHS();
7654 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7655 if (DRE->getDecl() != Variable)
7656 return;
7657 if (Expr *RHS = BinOp->getRHS()) {
7658 RHS = RHS->IgnoreParenCasts();
7659 llvm::APSInt Value;
7660 VarWillBeReased =
7661 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7662 }
7663 }
7664 }
John McCall31168b02011-06-15 23:02:42 +00007665 };
7666}
7667
7668/// Check whether the given argument is a block which captures a
7669/// variable.
7670static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7671 assert(owner.Variable && owner.Loc.isValid());
7672
7673 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007674
7675 // Look through [^{...} copy] and Block_copy(^{...}).
7676 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7677 Selector Cmd = ME->getSelector();
7678 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7679 e = ME->getInstanceReceiver();
7680 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007681 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007682 e = e->IgnoreParenCasts();
7683 }
7684 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7685 if (CE->getNumArgs() == 1) {
7686 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007687 if (Fn) {
7688 const IdentifierInfo *FnI = Fn->getIdentifier();
7689 if (FnI && FnI->isStr("_Block_copy")) {
7690 e = CE->getArg(0)->IgnoreParenCasts();
7691 }
7692 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007693 }
7694 }
7695
John McCall31168b02011-06-15 23:02:42 +00007696 BlockExpr *block = dyn_cast<BlockExpr>(e);
7697 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007698 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007699
7700 FindCaptureVisitor visitor(S.Context, owner.Variable);
7701 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007702 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007703}
7704
7705static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7706 RetainCycleOwner &owner) {
7707 assert(capturer);
7708 assert(owner.Variable && owner.Loc.isValid());
7709
7710 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7711 << owner.Variable << capturer->getSourceRange();
7712 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7713 << owner.Indirect << owner.Range;
7714}
7715
7716/// Check for a keyword selector that starts with the word 'add' or
7717/// 'set'.
7718static bool isSetterLikeSelector(Selector sel) {
7719 if (sel.isUnarySelector()) return false;
7720
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007721 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007722 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007723 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007724 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007725 else if (str.startswith("add")) {
7726 // Specially whitelist 'addOperationWithBlock:'.
7727 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7728 return false;
7729 str = str.substr(3);
7730 }
John McCall31168b02011-06-15 23:02:42 +00007731 else
7732 return false;
7733
7734 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007735 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007736}
7737
7738/// Check a message send to see if it's likely to cause a retain cycle.
7739void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7740 // Only check instance methods whose selector looks like a setter.
7741 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7742 return;
7743
7744 // Try to find a variable that the receiver is strongly owned by.
7745 RetainCycleOwner owner;
7746 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007747 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007748 return;
7749 } else {
7750 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7751 owner.Variable = getCurMethodDecl()->getSelfDecl();
7752 owner.Loc = msg->getSuperLoc();
7753 owner.Range = msg->getSuperLoc();
7754 }
7755
7756 // Check whether the receiver is captured by any of the arguments.
7757 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7758 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7759 return diagnoseRetainCycle(*this, capturer, owner);
7760}
7761
7762/// Check a property assign to see if it's likely to cause a retain cycle.
7763void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7764 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007765 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007766 return;
7767
7768 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7769 diagnoseRetainCycle(*this, capturer, owner);
7770}
7771
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007772void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7773 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007774 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007775 return;
7776
7777 // Because we don't have an expression for the variable, we have to set the
7778 // location explicitly here.
7779 Owner.Loc = Var->getLocation();
7780 Owner.Range = Var->getSourceRange();
7781
7782 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7783 diagnoseRetainCycle(*this, Capturer, Owner);
7784}
7785
Ted Kremenek9304da92012-12-21 08:04:28 +00007786static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7787 Expr *RHS, bool isProperty) {
7788 // Check if RHS is an Objective-C object literal, which also can get
7789 // immediately zapped in a weak reference. Note that we explicitly
7790 // allow ObjCStringLiterals, since those are designed to never really die.
7791 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007792
Ted Kremenek64873352012-12-21 22:46:35 +00007793 // This enum needs to match with the 'select' in
7794 // warn_objc_arc_literal_assign (off-by-1).
7795 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7796 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7797 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007798
7799 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007800 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007801 << (isProperty ? 0 : 1)
7802 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007803
7804 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007805}
7806
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007807static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7808 Qualifiers::ObjCLifetime LT,
7809 Expr *RHS, bool isProperty) {
7810 // Strip off any implicit cast added to get to the one ARC-specific.
7811 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7812 if (cast->getCastKind() == CK_ARCConsumeObject) {
7813 S.Diag(Loc, diag::warn_arc_retained_assign)
7814 << (LT == Qualifiers::OCL_ExplicitNone)
7815 << (isProperty ? 0 : 1)
7816 << RHS->getSourceRange();
7817 return true;
7818 }
7819 RHS = cast->getSubExpr();
7820 }
7821
7822 if (LT == Qualifiers::OCL_Weak &&
7823 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7824 return true;
7825
7826 return false;
7827}
7828
Ted Kremenekb36234d2012-12-21 08:04:20 +00007829bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7830 QualType LHS, Expr *RHS) {
7831 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7832
7833 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7834 return false;
7835
7836 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7837 return true;
7838
7839 return false;
7840}
7841
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007842void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7843 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007844 QualType LHSType;
7845 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007846 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007847 ObjCPropertyRefExpr *PRE
7848 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7849 if (PRE && !PRE->isImplicitProperty()) {
7850 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7851 if (PD)
7852 LHSType = PD->getType();
7853 }
7854
7855 if (LHSType.isNull())
7856 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007857
7858 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7859
7860 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007861 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007862 getCurFunction()->markSafeWeakUse(LHS);
7863 }
7864
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007865 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7866 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007867
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007868 // FIXME. Check for other life times.
7869 if (LT != Qualifiers::OCL_None)
7870 return;
7871
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007872 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007873 if (PRE->isImplicitProperty())
7874 return;
7875 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7876 if (!PD)
7877 return;
7878
Bill Wendling44426052012-12-20 19:22:21 +00007879 unsigned Attributes = PD->getPropertyAttributes();
7880 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007881 // when 'assign' attribute was not explicitly specified
7882 // by user, ignore it and rely on property type itself
7883 // for lifetime info.
7884 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7885 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7886 LHSType->isObjCRetainableType())
7887 return;
7888
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007889 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007890 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007891 Diag(Loc, diag::warn_arc_retained_property_assign)
7892 << RHS->getSourceRange();
7893 return;
7894 }
7895 RHS = cast->getSubExpr();
7896 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007897 }
Bill Wendling44426052012-12-20 19:22:21 +00007898 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007899 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7900 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007901 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007902 }
7903}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007904
7905//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7906
7907namespace {
7908bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7909 SourceLocation StmtLoc,
7910 const NullStmt *Body) {
7911 // Do not warn if the body is a macro that expands to nothing, e.g:
7912 //
7913 // #define CALL(x)
7914 // if (condition)
7915 // CALL(0);
7916 //
7917 if (Body->hasLeadingEmptyMacro())
7918 return false;
7919
7920 // Get line numbers of statement and body.
7921 bool StmtLineInvalid;
7922 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7923 &StmtLineInvalid);
7924 if (StmtLineInvalid)
7925 return false;
7926
7927 bool BodyLineInvalid;
7928 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7929 &BodyLineInvalid);
7930 if (BodyLineInvalid)
7931 return false;
7932
7933 // Warn if null statement and body are on the same line.
7934 if (StmtLine != BodyLine)
7935 return false;
7936
7937 return true;
7938}
7939} // Unnamed namespace
7940
7941void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7942 const Stmt *Body,
7943 unsigned DiagID) {
7944 // Since this is a syntactic check, don't emit diagnostic for template
7945 // instantiations, this just adds noise.
7946 if (CurrentInstantiationScope)
7947 return;
7948
7949 // The body should be a null statement.
7950 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7951 if (!NBody)
7952 return;
7953
7954 // Do the usual checks.
7955 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7956 return;
7957
7958 Diag(NBody->getSemiLoc(), DiagID);
7959 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7960}
7961
7962void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7963 const Stmt *PossibleBody) {
7964 assert(!CurrentInstantiationScope); // Ensured by caller
7965
7966 SourceLocation StmtLoc;
7967 const Stmt *Body;
7968 unsigned DiagID;
7969 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7970 StmtLoc = FS->getRParenLoc();
7971 Body = FS->getBody();
7972 DiagID = diag::warn_empty_for_body;
7973 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7974 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7975 Body = WS->getBody();
7976 DiagID = diag::warn_empty_while_body;
7977 } else
7978 return; // Neither `for' nor `while'.
7979
7980 // The body should be a null statement.
7981 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7982 if (!NBody)
7983 return;
7984
7985 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007986 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007987 return;
7988
7989 // Do the usual checks.
7990 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7991 return;
7992
7993 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7994 // noise level low, emit diagnostics only if for/while is followed by a
7995 // CompoundStmt, e.g.:
7996 // for (int i = 0; i < n; i++);
7997 // {
7998 // a(i);
7999 // }
8000 // or if for/while is followed by a statement with more indentation
8001 // than for/while itself:
8002 // for (int i = 0; i < n; i++);
8003 // a(i);
8004 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8005 if (!ProbableTypo) {
8006 bool BodyColInvalid;
8007 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8008 PossibleBody->getLocStart(),
8009 &BodyColInvalid);
8010 if (BodyColInvalid)
8011 return;
8012
8013 bool StmtColInvalid;
8014 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8015 S->getLocStart(),
8016 &StmtColInvalid);
8017 if (StmtColInvalid)
8018 return;
8019
8020 if (BodyCol > StmtCol)
8021 ProbableTypo = true;
8022 }
8023
8024 if (ProbableTypo) {
8025 Diag(NBody->getSemiLoc(), DiagID);
8026 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8027 }
8028}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008029
8030//===--- Layout compatibility ----------------------------------------------//
8031
8032namespace {
8033
8034bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8035
8036/// \brief Check if two enumeration types are layout-compatible.
8037bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8038 // C++11 [dcl.enum] p8:
8039 // Two enumeration types are layout-compatible if they have the same
8040 // underlying type.
8041 return ED1->isComplete() && ED2->isComplete() &&
8042 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8043}
8044
8045/// \brief Check if two fields are layout-compatible.
8046bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8047 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8048 return false;
8049
8050 if (Field1->isBitField() != Field2->isBitField())
8051 return false;
8052
8053 if (Field1->isBitField()) {
8054 // Make sure that the bit-fields are the same length.
8055 unsigned Bits1 = Field1->getBitWidthValue(C);
8056 unsigned Bits2 = Field2->getBitWidthValue(C);
8057
8058 if (Bits1 != Bits2)
8059 return false;
8060 }
8061
8062 return true;
8063}
8064
8065/// \brief Check if two standard-layout structs are layout-compatible.
8066/// (C++11 [class.mem] p17)
8067bool isLayoutCompatibleStruct(ASTContext &C,
8068 RecordDecl *RD1,
8069 RecordDecl *RD2) {
8070 // If both records are C++ classes, check that base classes match.
8071 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8072 // If one of records is a CXXRecordDecl we are in C++ mode,
8073 // thus the other one is a CXXRecordDecl, too.
8074 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8075 // Check number of base classes.
8076 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8077 return false;
8078
8079 // Check the base classes.
8080 for (CXXRecordDecl::base_class_const_iterator
8081 Base1 = D1CXX->bases_begin(),
8082 BaseEnd1 = D1CXX->bases_end(),
8083 Base2 = D2CXX->bases_begin();
8084 Base1 != BaseEnd1;
8085 ++Base1, ++Base2) {
8086 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8087 return false;
8088 }
8089 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8090 // If only RD2 is a C++ class, it should have zero base classes.
8091 if (D2CXX->getNumBases() > 0)
8092 return false;
8093 }
8094
8095 // Check the fields.
8096 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8097 Field2End = RD2->field_end(),
8098 Field1 = RD1->field_begin(),
8099 Field1End = RD1->field_end();
8100 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8101 if (!isLayoutCompatible(C, *Field1, *Field2))
8102 return false;
8103 }
8104 if (Field1 != Field1End || Field2 != Field2End)
8105 return false;
8106
8107 return true;
8108}
8109
8110/// \brief Check if two standard-layout unions are layout-compatible.
8111/// (C++11 [class.mem] p18)
8112bool isLayoutCompatibleUnion(ASTContext &C,
8113 RecordDecl *RD1,
8114 RecordDecl *RD2) {
8115 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008116 for (auto *Field2 : RD2->fields())
8117 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008118
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008119 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008120 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8121 I = UnmatchedFields.begin(),
8122 E = UnmatchedFields.end();
8123
8124 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008125 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008126 bool Result = UnmatchedFields.erase(*I);
8127 (void) Result;
8128 assert(Result);
8129 break;
8130 }
8131 }
8132 if (I == E)
8133 return false;
8134 }
8135
8136 return UnmatchedFields.empty();
8137}
8138
8139bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8140 if (RD1->isUnion() != RD2->isUnion())
8141 return false;
8142
8143 if (RD1->isUnion())
8144 return isLayoutCompatibleUnion(C, RD1, RD2);
8145 else
8146 return isLayoutCompatibleStruct(C, RD1, RD2);
8147}
8148
8149/// \brief Check if two types are layout-compatible in C++11 sense.
8150bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8151 if (T1.isNull() || T2.isNull())
8152 return false;
8153
8154 // C++11 [basic.types] p11:
8155 // If two types T1 and T2 are the same type, then T1 and T2 are
8156 // layout-compatible types.
8157 if (C.hasSameType(T1, T2))
8158 return true;
8159
8160 T1 = T1.getCanonicalType().getUnqualifiedType();
8161 T2 = T2.getCanonicalType().getUnqualifiedType();
8162
8163 const Type::TypeClass TC1 = T1->getTypeClass();
8164 const Type::TypeClass TC2 = T2->getTypeClass();
8165
8166 if (TC1 != TC2)
8167 return false;
8168
8169 if (TC1 == Type::Enum) {
8170 return isLayoutCompatible(C,
8171 cast<EnumType>(T1)->getDecl(),
8172 cast<EnumType>(T2)->getDecl());
8173 } else if (TC1 == Type::Record) {
8174 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8175 return false;
8176
8177 return isLayoutCompatible(C,
8178 cast<RecordType>(T1)->getDecl(),
8179 cast<RecordType>(T2)->getDecl());
8180 }
8181
8182 return false;
8183}
8184}
8185
8186//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8187
8188namespace {
8189/// \brief Given a type tag expression find the type tag itself.
8190///
8191/// \param TypeExpr Type tag expression, as it appears in user's code.
8192///
8193/// \param VD Declaration of an identifier that appears in a type tag.
8194///
8195/// \param MagicValue Type tag magic value.
8196bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8197 const ValueDecl **VD, uint64_t *MagicValue) {
8198 while(true) {
8199 if (!TypeExpr)
8200 return false;
8201
8202 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8203
8204 switch (TypeExpr->getStmtClass()) {
8205 case Stmt::UnaryOperatorClass: {
8206 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8207 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8208 TypeExpr = UO->getSubExpr();
8209 continue;
8210 }
8211 return false;
8212 }
8213
8214 case Stmt::DeclRefExprClass: {
8215 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8216 *VD = DRE->getDecl();
8217 return true;
8218 }
8219
8220 case Stmt::IntegerLiteralClass: {
8221 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8222 llvm::APInt MagicValueAPInt = IL->getValue();
8223 if (MagicValueAPInt.getActiveBits() <= 64) {
8224 *MagicValue = MagicValueAPInt.getZExtValue();
8225 return true;
8226 } else
8227 return false;
8228 }
8229
8230 case Stmt::BinaryConditionalOperatorClass:
8231 case Stmt::ConditionalOperatorClass: {
8232 const AbstractConditionalOperator *ACO =
8233 cast<AbstractConditionalOperator>(TypeExpr);
8234 bool Result;
8235 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8236 if (Result)
8237 TypeExpr = ACO->getTrueExpr();
8238 else
8239 TypeExpr = ACO->getFalseExpr();
8240 continue;
8241 }
8242 return false;
8243 }
8244
8245 case Stmt::BinaryOperatorClass: {
8246 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8247 if (BO->getOpcode() == BO_Comma) {
8248 TypeExpr = BO->getRHS();
8249 continue;
8250 }
8251 return false;
8252 }
8253
8254 default:
8255 return false;
8256 }
8257 }
8258}
8259
8260/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8261///
8262/// \param TypeExpr Expression that specifies a type tag.
8263///
8264/// \param MagicValues Registered magic values.
8265///
8266/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8267/// kind.
8268///
8269/// \param TypeInfo Information about the corresponding C type.
8270///
8271/// \returns true if the corresponding C type was found.
8272bool GetMatchingCType(
8273 const IdentifierInfo *ArgumentKind,
8274 const Expr *TypeExpr, const ASTContext &Ctx,
8275 const llvm::DenseMap<Sema::TypeTagMagicValue,
8276 Sema::TypeTagData> *MagicValues,
8277 bool &FoundWrongKind,
8278 Sema::TypeTagData &TypeInfo) {
8279 FoundWrongKind = false;
8280
8281 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008282 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008283
8284 uint64_t MagicValue;
8285
8286 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8287 return false;
8288
8289 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008290 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008291 if (I->getArgumentKind() != ArgumentKind) {
8292 FoundWrongKind = true;
8293 return false;
8294 }
8295 TypeInfo.Type = I->getMatchingCType();
8296 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8297 TypeInfo.MustBeNull = I->getMustBeNull();
8298 return true;
8299 }
8300 return false;
8301 }
8302
8303 if (!MagicValues)
8304 return false;
8305
8306 llvm::DenseMap<Sema::TypeTagMagicValue,
8307 Sema::TypeTagData>::const_iterator I =
8308 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8309 if (I == MagicValues->end())
8310 return false;
8311
8312 TypeInfo = I->second;
8313 return true;
8314}
8315} // unnamed namespace
8316
8317void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8318 uint64_t MagicValue, QualType Type,
8319 bool LayoutCompatible,
8320 bool MustBeNull) {
8321 if (!TypeTagForDatatypeMagicValues)
8322 TypeTagForDatatypeMagicValues.reset(
8323 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8324
8325 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8326 (*TypeTagForDatatypeMagicValues)[Magic] =
8327 TypeTagData(Type, LayoutCompatible, MustBeNull);
8328}
8329
8330namespace {
8331bool IsSameCharType(QualType T1, QualType T2) {
8332 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8333 if (!BT1)
8334 return false;
8335
8336 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8337 if (!BT2)
8338 return false;
8339
8340 BuiltinType::Kind T1Kind = BT1->getKind();
8341 BuiltinType::Kind T2Kind = BT2->getKind();
8342
8343 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8344 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8345 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8346 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8347}
8348} // unnamed namespace
8349
8350void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8351 const Expr * const *ExprArgs) {
8352 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8353 bool IsPointerAttr = Attr->getIsPointer();
8354
8355 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8356 bool FoundWrongKind;
8357 TypeTagData TypeInfo;
8358 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8359 TypeTagForDatatypeMagicValues.get(),
8360 FoundWrongKind, TypeInfo)) {
8361 if (FoundWrongKind)
8362 Diag(TypeTagExpr->getExprLoc(),
8363 diag::warn_type_tag_for_datatype_wrong_kind)
8364 << TypeTagExpr->getSourceRange();
8365 return;
8366 }
8367
8368 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8369 if (IsPointerAttr) {
8370 // Skip implicit cast of pointer to `void *' (as a function argument).
8371 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008372 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008373 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008374 ArgumentExpr = ICE->getSubExpr();
8375 }
8376 QualType ArgumentType = ArgumentExpr->getType();
8377
8378 // Passing a `void*' pointer shouldn't trigger a warning.
8379 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8380 return;
8381
8382 if (TypeInfo.MustBeNull) {
8383 // Type tag with matching void type requires a null pointer.
8384 if (!ArgumentExpr->isNullPointerConstant(Context,
8385 Expr::NPC_ValueDependentIsNotNull)) {
8386 Diag(ArgumentExpr->getExprLoc(),
8387 diag::warn_type_safety_null_pointer_required)
8388 << ArgumentKind->getName()
8389 << ArgumentExpr->getSourceRange()
8390 << TypeTagExpr->getSourceRange();
8391 }
8392 return;
8393 }
8394
8395 QualType RequiredType = TypeInfo.Type;
8396 if (IsPointerAttr)
8397 RequiredType = Context.getPointerType(RequiredType);
8398
8399 bool mismatch = false;
8400 if (!TypeInfo.LayoutCompatible) {
8401 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8402
8403 // C++11 [basic.fundamental] p1:
8404 // Plain char, signed char, and unsigned char are three distinct types.
8405 //
8406 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8407 // char' depending on the current char signedness mode.
8408 if (mismatch)
8409 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8410 RequiredType->getPointeeType())) ||
8411 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8412 mismatch = false;
8413 } else
8414 if (IsPointerAttr)
8415 mismatch = !isLayoutCompatible(Context,
8416 ArgumentType->getPointeeType(),
8417 RequiredType->getPointeeType());
8418 else
8419 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8420
8421 if (mismatch)
8422 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008423 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008424 << TypeInfo.LayoutCompatible << RequiredType
8425 << ArgumentExpr->getSourceRange()
8426 << TypeTagExpr->getSourceRange();
8427}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008428