blob: 0483341cef1b3698a993861207e327d75fa8c3e0 [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:
192 if (SemaBuiltinAssume(TheCall))
193 return ExprError();
194 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000195 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000196 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000197 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000198 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000199 case Builtin::BI__builtin_longjmp:
200 if (SemaBuiltinLongjmp(TheCall))
201 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000202 break;
John McCallbebede42011-02-26 05:39:39 +0000203
204 case Builtin::BI__builtin_classify_type:
205 if (checkArgCount(*this, TheCall, 1)) return true;
206 TheCall->setType(Context.IntTy);
207 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000208 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000209 if (checkArgCount(*this, TheCall, 1)) return true;
210 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000211 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_add_1:
214 case Builtin::BI__sync_fetch_and_add_2:
215 case Builtin::BI__sync_fetch_and_add_4:
216 case Builtin::BI__sync_fetch_and_add_8:
217 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_sub_1:
220 case Builtin::BI__sync_fetch_and_sub_2:
221 case Builtin::BI__sync_fetch_and_sub_4:
222 case Builtin::BI__sync_fetch_and_sub_8:
223 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_fetch_and_or_1:
226 case Builtin::BI__sync_fetch_and_or_2:
227 case Builtin::BI__sync_fetch_and_or_4:
228 case Builtin::BI__sync_fetch_and_or_8:
229 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_fetch_and_and_1:
232 case Builtin::BI__sync_fetch_and_and_2:
233 case Builtin::BI__sync_fetch_and_and_4:
234 case Builtin::BI__sync_fetch_and_and_8:
235 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_fetch_and_xor_1:
238 case Builtin::BI__sync_fetch_and_xor_2:
239 case Builtin::BI__sync_fetch_and_xor_4:
240 case Builtin::BI__sync_fetch_and_xor_8:
241 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_add_and_fetch_1:
244 case Builtin::BI__sync_add_and_fetch_2:
245 case Builtin::BI__sync_add_and_fetch_4:
246 case Builtin::BI__sync_add_and_fetch_8:
247 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_sub_and_fetch_1:
250 case Builtin::BI__sync_sub_and_fetch_2:
251 case Builtin::BI__sync_sub_and_fetch_4:
252 case Builtin::BI__sync_sub_and_fetch_8:
253 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_and_and_fetch_1:
256 case Builtin::BI__sync_and_and_fetch_2:
257 case Builtin::BI__sync_and_and_fetch_4:
258 case Builtin::BI__sync_and_and_fetch_8:
259 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_or_and_fetch_1:
262 case Builtin::BI__sync_or_and_fetch_2:
263 case Builtin::BI__sync_or_and_fetch_4:
264 case Builtin::BI__sync_or_and_fetch_8:
265 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_xor_and_fetch_1:
268 case Builtin::BI__sync_xor_and_fetch_2:
269 case Builtin::BI__sync_xor_and_fetch_4:
270 case Builtin::BI__sync_xor_and_fetch_8:
271 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_val_compare_and_swap_1:
274 case Builtin::BI__sync_val_compare_and_swap_2:
275 case Builtin::BI__sync_val_compare_and_swap_4:
276 case Builtin::BI__sync_val_compare_and_swap_8:
277 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000278 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_bool_compare_and_swap_1:
280 case Builtin::BI__sync_bool_compare_and_swap_2:
281 case Builtin::BI__sync_bool_compare_and_swap_4:
282 case Builtin::BI__sync_bool_compare_and_swap_8:
283 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000284 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000285 case Builtin::BI__sync_lock_test_and_set_1:
286 case Builtin::BI__sync_lock_test_and_set_2:
287 case Builtin::BI__sync_lock_test_and_set_4:
288 case Builtin::BI__sync_lock_test_and_set_8:
289 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000290 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000291 case Builtin::BI__sync_lock_release_1:
292 case Builtin::BI__sync_lock_release_2:
293 case Builtin::BI__sync_lock_release_4:
294 case Builtin::BI__sync_lock_release_8:
295 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000296 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000297 case Builtin::BI__sync_swap_1:
298 case Builtin::BI__sync_swap_2:
299 case Builtin::BI__sync_swap_4:
300 case Builtin::BI__sync_swap_8:
301 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000302 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000303#define BUILTIN(ID, TYPE, ATTRS)
304#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
305 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000306 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000307#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000308 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000309 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000310 return ExprError();
311 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000312 case Builtin::BI__builtin_addressof:
313 if (SemaBuiltinAddressof(*this, TheCall))
314 return ExprError();
315 break;
Richard Smith760520b2014-06-03 23:27:44 +0000316 case Builtin::BI__builtin_operator_new:
317 case Builtin::BI__builtin_operator_delete:
318 if (!getLangOpts().CPlusPlus) {
319 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
320 << (BuiltinID == Builtin::BI__builtin_operator_new
321 ? "__builtin_operator_new"
322 : "__builtin_operator_delete")
323 << "C++";
324 return ExprError();
325 }
326 // CodeGen assumes it can find the global new and delete to call,
327 // so ensure that they are declared.
328 DeclareGlobalNewDelete();
329 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000330 }
Richard Smith760520b2014-06-03 23:27:44 +0000331
Nate Begeman4904e322010-06-08 02:47:44 +0000332 // Since the target specific builtins for each arch overlap, only check those
333 // of the arch we are compiling for.
334 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000335 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000336 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000337 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000338 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000339 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000340 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
341 return ExprError();
342 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000343 case llvm::Triple::aarch64:
344 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000345 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000346 return ExprError();
347 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000348 case llvm::Triple::mips:
349 case llvm::Triple::mipsel:
350 case llvm::Triple::mips64:
351 case llvm::Triple::mips64el:
352 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
353 return ExprError();
354 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000355 case llvm::Triple::x86:
356 case llvm::Triple::x86_64:
357 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
358 return ExprError();
359 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000360 default:
361 break;
362 }
363 }
364
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000365 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000366}
367
Nate Begeman91e1fea2010-06-14 05:21:25 +0000368// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000369static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000370 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000371 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000372 switch (Type.getEltType()) {
373 case NeonTypeFlags::Int8:
374 case NeonTypeFlags::Poly8:
375 return shift ? 7 : (8 << IsQuad) - 1;
376 case NeonTypeFlags::Int16:
377 case NeonTypeFlags::Poly16:
378 return shift ? 15 : (4 << IsQuad) - 1;
379 case NeonTypeFlags::Int32:
380 return shift ? 31 : (2 << IsQuad) - 1;
381 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000382 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000383 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000384 case NeonTypeFlags::Poly128:
385 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000386 case NeonTypeFlags::Float16:
387 assert(!shift && "cannot shift float types!");
388 return (4 << IsQuad) - 1;
389 case NeonTypeFlags::Float32:
390 assert(!shift && "cannot shift float types!");
391 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000392 case NeonTypeFlags::Float64:
393 assert(!shift && "cannot shift float types!");
394 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000395 }
David Blaikie8a40f702012-01-17 06:56:22 +0000396 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000397}
398
Bob Wilsone4d77232011-11-08 05:04:11 +0000399/// getNeonEltType - Return the QualType corresponding to the elements of
400/// the vector type specified by the NeonTypeFlags. This is used to check
401/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000402static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000403 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000404 switch (Flags.getEltType()) {
405 case NeonTypeFlags::Int8:
406 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
407 case NeonTypeFlags::Int16:
408 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
409 case NeonTypeFlags::Int32:
410 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
411 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000412 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000413 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
414 else
415 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
416 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000417 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000418 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000419 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000420 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000421 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000422 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000423 case NeonTypeFlags::Poly128:
424 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000425 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000427 case NeonTypeFlags::Float32:
428 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000429 case NeonTypeFlags::Float64:
430 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000431 }
David Blaikie8a40f702012-01-17 06:56:22 +0000432 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000433}
434
Tim Northover12670412014-02-19 10:37:05 +0000435bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000436 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000437 uint64_t mask = 0;
438 unsigned TV = 0;
439 int PtrArgNum = -1;
440 bool HasConstPtr = false;
441 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000442#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000443#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000444#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000445 }
446
447 // For NEON intrinsics which are overloaded on vector element type, validate
448 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000449 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000450 if (mask) {
451 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
452 return true;
453
454 TV = Result.getLimitedValue(64);
455 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
456 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000457 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000458 }
459
460 if (PtrArgNum >= 0) {
461 // Check that pointer arguments have the specified type.
462 Expr *Arg = TheCall->getArg(PtrArgNum);
463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
464 Arg = ICE->getSubExpr();
465 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
466 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000467
Tim Northovera2ee4332014-03-29 15:09:45 +0000468 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000469 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000470 bool IsInt64Long =
471 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
472 QualType EltTy =
473 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000474 if (HasConstPtr)
475 EltTy = EltTy.withConst();
476 QualType LHSTy = Context.getPointerType(EltTy);
477 AssignConvertType ConvTy;
478 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
479 if (RHS.isInvalid())
480 return true;
481 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
482 RHS.get(), AA_Assigning))
483 return true;
484 }
485
486 // For NEON intrinsics which take an immediate value as part of the
487 // instruction, range check them here.
488 unsigned i = 0, l = 0, u = 0;
489 switch (BuiltinID) {
490 default:
491 return false;
Tim Northover12670412014-02-19 10:37:05 +0000492#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000493#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000494#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000495 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000496
Richard Sandiford28940af2014-04-16 08:47:51 +0000497 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000498}
499
Tim Northovera2ee4332014-03-29 15:09:45 +0000500bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
501 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000502 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000503 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000504 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000505 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000506 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000507 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
508 BuiltinID == AArch64::BI__builtin_arm_strex ||
509 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000510 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000511 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000512 BuiltinID == ARM::BI__builtin_arm_ldaex ||
513 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
514 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000515
516 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
517
518 // Ensure that we have the proper number of arguments.
519 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
520 return true;
521
522 // Inspect the pointer argument of the atomic builtin. This should always be
523 // a pointer type, whose element is an integral scalar or pointer type.
524 // Because it is a pointer type, we don't have to worry about any implicit
525 // casts here.
526 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
527 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
528 if (PointerArgRes.isInvalid())
529 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000530 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000531
532 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
533 if (!pointerType) {
534 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
535 << PointerArg->getType() << PointerArg->getSourceRange();
536 return true;
537 }
538
539 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
540 // task is to insert the appropriate casts into the AST. First work out just
541 // what the appropriate type is.
542 QualType ValType = pointerType->getPointeeType();
543 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
544 if (IsLdrex)
545 AddrType.addConst();
546
547 // Issue a warning if the cast is dodgy.
548 CastKind CastNeeded = CK_NoOp;
549 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
550 CastNeeded = CK_BitCast;
551 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
552 << PointerArg->getType()
553 << Context.getPointerType(AddrType)
554 << AA_Passing << PointerArg->getSourceRange();
555 }
556
557 // Finally, do the cast and replace the argument with the corrected version.
558 AddrType = Context.getPointerType(AddrType);
559 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
560 if (PointerArgRes.isInvalid())
561 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000562 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000563
564 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
565
566 // In general, we allow ints, floats and pointers to be loaded and stored.
567 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
568 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
569 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
570 << PointerArg->getType() << PointerArg->getSourceRange();
571 return true;
572 }
573
574 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000575 if (Context.getTypeSize(ValType) > MaxWidth) {
576 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000577 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
578 << PointerArg->getType() << PointerArg->getSourceRange();
579 return true;
580 }
581
582 switch (ValType.getObjCLifetime()) {
583 case Qualifiers::OCL_None:
584 case Qualifiers::OCL_ExplicitNone:
585 // okay
586 break;
587
588 case Qualifiers::OCL_Weak:
589 case Qualifiers::OCL_Strong:
590 case Qualifiers::OCL_Autoreleasing:
591 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
592 << ValType << PointerArg->getSourceRange();
593 return true;
594 }
595
596
597 if (IsLdrex) {
598 TheCall->setType(ValType);
599 return false;
600 }
601
602 // Initialize the argument to be stored.
603 ExprResult ValArg = TheCall->getArg(0);
604 InitializedEntity Entity = InitializedEntity::InitializeParameter(
605 Context, ValType, /*consume*/ false);
606 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
607 if (ValArg.isInvalid())
608 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000609 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000610
611 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
612 // but the custom checker bypasses all default analysis.
613 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000614 return false;
615}
616
Nate Begeman4904e322010-06-08 02:47:44 +0000617bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000618 llvm::APSInt Result;
619
Tim Northover6aacd492013-07-16 09:47:53 +0000620 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000621 BuiltinID == ARM::BI__builtin_arm_ldaex ||
622 BuiltinID == ARM::BI__builtin_arm_strex ||
623 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000624 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000625 }
626
Tim Northover12670412014-02-19 10:37:05 +0000627 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
628 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000629
Yi Kong4efadfb2014-07-03 16:01:25 +0000630 // For intrinsics which take an immediate value as part of the instruction,
631 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000632 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000633 switch (BuiltinID) {
634 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000635 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
636 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000637 case ARM::BI__builtin_arm_vcvtr_f:
638 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000639 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000640 case ARM::BI__builtin_arm_dsb:
641 case ARM::BI__builtin_arm_isb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000642 }
Nate Begemand773fe62010-06-13 04:47:52 +0000643
Nate Begemanf568b072010-08-03 21:32:34 +0000644 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000645 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000646}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000647
Tim Northover573cbee2014-05-24 12:52:07 +0000648bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000649 CallExpr *TheCall) {
650 llvm::APSInt Result;
651
Tim Northover573cbee2014-05-24 12:52:07 +0000652 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000653 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
654 BuiltinID == AArch64::BI__builtin_arm_strex ||
655 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000656 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
657 }
658
659 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
660 return true;
661
Yi Kong19a29ac2014-07-17 10:52:06 +0000662 // For intrinsics which take an immediate value as part of the instruction,
663 // range check them here.
664 unsigned i = 0, l = 0, u = 0;
665 switch (BuiltinID) {
666 default: return false;
667 case AArch64::BI__builtin_arm_dmb:
668 case AArch64::BI__builtin_arm_dsb:
669 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
670 }
671
672 // FIXME: VFP Intrinsics should error if VFP not present.
673 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000674}
675
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000676bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
677 unsigned i = 0, l = 0, u = 0;
678 switch (BuiltinID) {
679 default: return false;
680 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
681 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000682 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
683 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
684 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
685 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
686 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000687 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000688
Richard Sandiford28940af2014-04-16 08:47:51 +0000689 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000690}
691
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000692bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
693 switch (BuiltinID) {
694 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000695 // This is declared to take (const char*, int)
696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000697 }
698 return false;
699}
700
Richard Smith55ce3522012-06-25 20:30:08 +0000701/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
702/// parameter with the FormatAttr's correct format_idx and firstDataArg.
703/// Returns true when the format fits the function and the FormatStringInfo has
704/// been populated.
705bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
706 FormatStringInfo *FSI) {
707 FSI->HasVAListArg = Format->getFirstArg() == 0;
708 FSI->FormatIdx = Format->getFormatIdx() - 1;
709 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000710
Richard Smith55ce3522012-06-25 20:30:08 +0000711 // The way the format attribute works in GCC, the implicit this argument
712 // of member functions is counted. However, it doesn't appear in our own
713 // lists, so decrement format_idx in that case.
714 if (IsCXXMember) {
715 if(FSI->FormatIdx == 0)
716 return false;
717 --FSI->FormatIdx;
718 if (FSI->FirstDataArg != 0)
719 --FSI->FirstDataArg;
720 }
721 return true;
722}
Mike Stump11289f42009-09-09 15:08:12 +0000723
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000724/// Checks if a the given expression evaluates to null.
725///
726/// \brief Returns true if the value evaluates to null.
727static bool CheckNonNullExpr(Sema &S,
728 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000729 // As a special case, transparent unions initialized with zero are
730 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000731 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000732 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
733 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000734 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000735 if (const InitListExpr *ILE =
736 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000737 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000738 }
739
740 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000741 return (!Expr->isValueDependent() &&
742 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
743 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000744}
745
746static void CheckNonNullArgument(Sema &S,
747 const Expr *ArgExpr,
748 SourceLocation CallSiteLoc) {
749 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000750 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
751}
752
Ted Kremenek2bc73332014-01-17 06:24:43 +0000753static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000754 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000755 const Expr * const *ExprArgs,
756 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000757 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000758 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000759 for (const auto &Val : NonNull->args())
760 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000761 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000762
763 // Check the attributes on the parameters.
764 ArrayRef<ParmVarDecl*> parms;
765 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
766 parms = FD->parameters();
767 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
768 parms = MD->parameters();
769
770 unsigned argIndex = 0;
771 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
772 I != E; ++I, ++argIndex) {
773 const ParmVarDecl *PVD = *I;
774 if (PVD->hasAttr<NonNullAttr>())
775 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
776 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000777}
778
Richard Smith55ce3522012-06-25 20:30:08 +0000779/// Handles the checks for format strings, non-POD arguments to vararg
780/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000781void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
782 unsigned NumParams, bool IsMemberFunction,
783 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000784 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000785 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000786 if (CurContext->isDependentContext())
787 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000788
Ted Kremenekb8176da2010-09-09 04:33:05 +0000789 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000790 llvm::SmallBitVector CheckedVarArgs;
791 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000792 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000793 // Only create vector if there are format attributes.
794 CheckedVarArgs.resize(Args.size());
795
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000796 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000797 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000798 }
Richard Smithd7293d72013-08-05 18:49:43 +0000799 }
Richard Smith55ce3522012-06-25 20:30:08 +0000800
801 // Refuse POD arguments that weren't caught by the format string
802 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000803 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000804 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000805 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000806 if (const Expr *Arg = Args[ArgIdx]) {
807 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
808 checkVariadicArgument(Arg, CallType);
809 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000810 }
Richard Smithd7293d72013-08-05 18:49:43 +0000811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Richard Trieu41bc0992013-06-22 00:20:41 +0000813 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000814 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000815
Richard Trieu41bc0992013-06-22 00:20:41 +0000816 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000817 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
818 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000819 }
Richard Smith55ce3522012-06-25 20:30:08 +0000820}
821
822/// CheckConstructorCall - Check a constructor call for correctness and safety
823/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000824void Sema::CheckConstructorCall(FunctionDecl *FDecl,
825 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000826 const FunctionProtoType *Proto,
827 SourceLocation Loc) {
828 VariadicCallType CallType =
829 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000830 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000831 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
832}
833
834/// CheckFunctionCall - Check a direct function call for various correctness
835/// and safety properties not strictly enforced by the C type system.
836bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
837 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000838 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
839 isa<CXXMethodDecl>(FDecl);
840 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
841 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000842 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
843 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000844 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000845 Expr** Args = TheCall->getArgs();
846 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000847 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000848 // If this is a call to a member operator, hide the first argument
849 // from checkCall.
850 // FIXME: Our choice of AST representation here is less than ideal.
851 ++Args;
852 --NumArgs;
853 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000854 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000855 IsMemberFunction, TheCall->getRParenLoc(),
856 TheCall->getCallee()->getSourceRange(), CallType);
857
858 IdentifierInfo *FnInfo = FDecl->getIdentifier();
859 // None of the checks below are needed for functions that don't have
860 // simple names (e.g., C++ conversion functions).
861 if (!FnInfo)
862 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000863
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000864 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
865
Anna Zaks22122702012-01-17 00:37:07 +0000866 unsigned CMId = FDecl->getMemoryFunctionKind();
867 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000868 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000869
Anna Zaks201d4892012-01-13 21:52:01 +0000870 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000871 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000872 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000873 else if (CMId == Builtin::BIstrncat)
874 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000875 else
Anna Zaks22122702012-01-17 00:37:07 +0000876 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000877
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000878 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000879}
880
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000881bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000882 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000883 VariadicCallType CallType =
884 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000885
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000886 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000887 /*IsMemberFunction=*/false,
888 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000889
890 return false;
891}
892
Richard Trieu664c4c62013-06-20 21:03:13 +0000893bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
894 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000895 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
896 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000897 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000898
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000899 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000900 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000901 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000902
Richard Trieu664c4c62013-06-20 21:03:13 +0000903 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000904 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000905 CallType = VariadicDoesNotApply;
906 } else if (Ty->isBlockPointerType()) {
907 CallType = VariadicBlock;
908 } else { // Ty->isFunctionPointerType()
909 CallType = VariadicFunction;
910 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000911 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912
Alp Toker9cacbab2014-01-20 20:26:09 +0000913 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
914 TheCall->getNumArgs()),
915 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000916 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000917
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000918 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000919}
920
Richard Trieu41bc0992013-06-22 00:20:41 +0000921/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
922/// such as function pointers returned from functions.
923bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000924 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000925 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000926 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000927
Craig Topperc3ec1492014-05-26 06:22:03 +0000928 checkCall(/*FDecl=*/nullptr,
929 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
930 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000931 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000932 TheCall->getCallee()->getSourceRange(), CallType);
933
934 return false;
935}
936
Tim Northovere94a34c2014-03-11 10:49:14 +0000937static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
938 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
939 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
940 return false;
941
942 switch (Op) {
943 case AtomicExpr::AO__c11_atomic_init:
944 llvm_unreachable("There is no ordering argument for an init");
945
946 case AtomicExpr::AO__c11_atomic_load:
947 case AtomicExpr::AO__atomic_load_n:
948 case AtomicExpr::AO__atomic_load:
949 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
950 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
951
952 case AtomicExpr::AO__c11_atomic_store:
953 case AtomicExpr::AO__atomic_store:
954 case AtomicExpr::AO__atomic_store_n:
955 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
956 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
957 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
958
959 default:
960 return true;
961 }
962}
963
Richard Smithfeea8832012-04-12 05:08:17 +0000964ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
965 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000966 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
967 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000968
Richard Smithfeea8832012-04-12 05:08:17 +0000969 // All these operations take one of the following forms:
970 enum {
971 // C __c11_atomic_init(A *, C)
972 Init,
973 // C __c11_atomic_load(A *, int)
974 Load,
975 // void __atomic_load(A *, CP, int)
976 Copy,
977 // C __c11_atomic_add(A *, M, int)
978 Arithmetic,
979 // C __atomic_exchange_n(A *, CP, int)
980 Xchg,
981 // void __atomic_exchange(A *, C *, CP, int)
982 GNUXchg,
983 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
984 C11CmpXchg,
985 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
986 GNUCmpXchg
987 } Form = Init;
988 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
989 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
990 // where:
991 // C is an appropriate type,
992 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
993 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
994 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
995 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000996
Richard Smithfeea8832012-04-12 05:08:17 +0000997 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
998 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
999 && "need to update code for modified C11 atomics");
1000 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1001 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1002 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1003 Op == AtomicExpr::AO__atomic_store_n ||
1004 Op == AtomicExpr::AO__atomic_exchange_n ||
1005 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1006 bool IsAddSub = false;
1007
1008 switch (Op) {
1009 case AtomicExpr::AO__c11_atomic_init:
1010 Form = Init;
1011 break;
1012
1013 case AtomicExpr::AO__c11_atomic_load:
1014 case AtomicExpr::AO__atomic_load_n:
1015 Form = Load;
1016 break;
1017
1018 case AtomicExpr::AO__c11_atomic_store:
1019 case AtomicExpr::AO__atomic_load:
1020 case AtomicExpr::AO__atomic_store:
1021 case AtomicExpr::AO__atomic_store_n:
1022 Form = Copy;
1023 break;
1024
1025 case AtomicExpr::AO__c11_atomic_fetch_add:
1026 case AtomicExpr::AO__c11_atomic_fetch_sub:
1027 case AtomicExpr::AO__atomic_fetch_add:
1028 case AtomicExpr::AO__atomic_fetch_sub:
1029 case AtomicExpr::AO__atomic_add_fetch:
1030 case AtomicExpr::AO__atomic_sub_fetch:
1031 IsAddSub = true;
1032 // Fall through.
1033 case AtomicExpr::AO__c11_atomic_fetch_and:
1034 case AtomicExpr::AO__c11_atomic_fetch_or:
1035 case AtomicExpr::AO__c11_atomic_fetch_xor:
1036 case AtomicExpr::AO__atomic_fetch_and:
1037 case AtomicExpr::AO__atomic_fetch_or:
1038 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001039 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001040 case AtomicExpr::AO__atomic_and_fetch:
1041 case AtomicExpr::AO__atomic_or_fetch:
1042 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001043 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001044 Form = Arithmetic;
1045 break;
1046
1047 case AtomicExpr::AO__c11_atomic_exchange:
1048 case AtomicExpr::AO__atomic_exchange_n:
1049 Form = Xchg;
1050 break;
1051
1052 case AtomicExpr::AO__atomic_exchange:
1053 Form = GNUXchg;
1054 break;
1055
1056 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1057 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1058 Form = C11CmpXchg;
1059 break;
1060
1061 case AtomicExpr::AO__atomic_compare_exchange:
1062 case AtomicExpr::AO__atomic_compare_exchange_n:
1063 Form = GNUCmpXchg;
1064 break;
1065 }
1066
1067 // Check we have the right number of arguments.
1068 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001069 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001070 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001071 << TheCall->getCallee()->getSourceRange();
1072 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001073 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1074 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001075 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001076 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001077 << TheCall->getCallee()->getSourceRange();
1078 return ExprError();
1079 }
1080
Richard Smithfeea8832012-04-12 05:08:17 +00001081 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001082 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001083 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1084 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1085 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001086 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001087 << Ptr->getType() << Ptr->getSourceRange();
1088 return ExprError();
1089 }
1090
Richard Smithfeea8832012-04-12 05:08:17 +00001091 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1092 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1093 QualType ValType = AtomTy; // 'C'
1094 if (IsC11) {
1095 if (!AtomTy->isAtomicType()) {
1096 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1097 << Ptr->getType() << Ptr->getSourceRange();
1098 return ExprError();
1099 }
Richard Smithe00921a2012-09-15 06:09:58 +00001100 if (AtomTy.isConstQualified()) {
1101 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1102 << Ptr->getType() << Ptr->getSourceRange();
1103 return ExprError();
1104 }
Richard Smithfeea8832012-04-12 05:08:17 +00001105 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001106 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001107
Richard Smithfeea8832012-04-12 05:08:17 +00001108 // For an arithmetic operation, the implied arithmetic must be well-formed.
1109 if (Form == Arithmetic) {
1110 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1111 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1112 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1113 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1114 return ExprError();
1115 }
1116 if (!IsAddSub && !ValType->isIntegerType()) {
1117 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1118 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1119 return ExprError();
1120 }
1121 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1122 // For __atomic_*_n operations, the value type must be a scalar integral or
1123 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1126 return ExprError();
1127 }
1128
Eli Friedmanaa769812013-09-11 03:49:34 +00001129 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1130 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001131 // For GNU atomics, require a trivially-copyable type. This is not part of
1132 // the GNU atomics specification, but we enforce it for sanity.
1133 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001134 << Ptr->getType() << Ptr->getSourceRange();
1135 return ExprError();
1136 }
1137
Richard Smithfeea8832012-04-12 05:08:17 +00001138 // FIXME: For any builtin other than a load, the ValType must not be
1139 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001140
1141 switch (ValType.getObjCLifetime()) {
1142 case Qualifiers::OCL_None:
1143 case Qualifiers::OCL_ExplicitNone:
1144 // okay
1145 break;
1146
1147 case Qualifiers::OCL_Weak:
1148 case Qualifiers::OCL_Strong:
1149 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001150 // FIXME: Can this happen? By this point, ValType should be known
1151 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001152 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1153 << ValType << Ptr->getSourceRange();
1154 return ExprError();
1155 }
1156
1157 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001158 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001159 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001160 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001161 ResultType = Context.BoolTy;
1162
Richard Smithfeea8832012-04-12 05:08:17 +00001163 // The type of a parameter passed 'by value'. In the GNU atomics, such
1164 // arguments are actually passed as pointers.
1165 QualType ByValType = ValType; // 'CP'
1166 if (!IsC11 && !IsN)
1167 ByValType = Ptr->getType();
1168
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001169 // The first argument --- the pointer --- has a fixed type; we
1170 // deduce the types of the rest of the arguments accordingly. Walk
1171 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001172 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001173 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001174 if (i < NumVals[Form] + 1) {
1175 switch (i) {
1176 case 1:
1177 // The second argument is the non-atomic operand. For arithmetic, this
1178 // is always passed by value, and for a compare_exchange it is always
1179 // passed by address. For the rest, GNU uses by-address and C11 uses
1180 // by-value.
1181 assert(Form != Load);
1182 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1183 Ty = ValType;
1184 else if (Form == Copy || Form == Xchg)
1185 Ty = ByValType;
1186 else if (Form == Arithmetic)
1187 Ty = Context.getPointerDiffType();
1188 else
1189 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1190 break;
1191 case 2:
1192 // The third argument to compare_exchange / GNU exchange is a
1193 // (pointer to a) desired value.
1194 Ty = ByValType;
1195 break;
1196 case 3:
1197 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1198 Ty = Context.BoolTy;
1199 break;
1200 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001201 } else {
1202 // The order(s) are always converted to int.
1203 Ty = Context.IntTy;
1204 }
Richard Smithfeea8832012-04-12 05:08:17 +00001205
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001206 InitializedEntity Entity =
1207 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001208 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001209 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1210 if (Arg.isInvalid())
1211 return true;
1212 TheCall->setArg(i, Arg.get());
1213 }
1214
Richard Smithfeea8832012-04-12 05:08:17 +00001215 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001216 SmallVector<Expr*, 5> SubExprs;
1217 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001218 switch (Form) {
1219 case Init:
1220 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001221 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001222 break;
1223 case Load:
1224 SubExprs.push_back(TheCall->getArg(1)); // Order
1225 break;
1226 case Copy:
1227 case Arithmetic:
1228 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001229 SubExprs.push_back(TheCall->getArg(2)); // Order
1230 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001231 break;
1232 case GNUXchg:
1233 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1234 SubExprs.push_back(TheCall->getArg(3)); // Order
1235 SubExprs.push_back(TheCall->getArg(1)); // Val1
1236 SubExprs.push_back(TheCall->getArg(2)); // Val2
1237 break;
1238 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001239 SubExprs.push_back(TheCall->getArg(3)); // Order
1240 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001241 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001242 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001243 break;
1244 case GNUCmpXchg:
1245 SubExprs.push_back(TheCall->getArg(4)); // Order
1246 SubExprs.push_back(TheCall->getArg(1)); // Val1
1247 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1248 SubExprs.push_back(TheCall->getArg(2)); // Val2
1249 SubExprs.push_back(TheCall->getArg(3)); // Weak
1250 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001251 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001252
1253 if (SubExprs.size() >= 2 && Form != Init) {
1254 llvm::APSInt Result(32);
1255 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1256 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001257 Diag(SubExprs[1]->getLocStart(),
1258 diag::warn_atomic_op_has_invalid_memory_order)
1259 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001260 }
1261
Fariborz Jahanian615de762013-05-28 17:37:39 +00001262 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1263 SubExprs, ResultType, Op,
1264 TheCall->getRParenLoc());
1265
1266 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1267 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1268 Context.AtomicUsesUnsupportedLibcall(AE))
1269 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1270 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001271
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001272 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001273}
1274
1275
John McCall29ad95b2011-08-27 01:09:30 +00001276/// checkBuiltinArgument - Given a call to a builtin function, perform
1277/// normal type-checking on the given argument, updating the call in
1278/// place. This is useful when a builtin function requires custom
1279/// type-checking for some of its arguments but not necessarily all of
1280/// them.
1281///
1282/// Returns true on error.
1283static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1284 FunctionDecl *Fn = E->getDirectCallee();
1285 assert(Fn && "builtin call without direct callee!");
1286
1287 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1288 InitializedEntity Entity =
1289 InitializedEntity::InitializeParameter(S.Context, Param);
1290
1291 ExprResult Arg = E->getArg(0);
1292 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1293 if (Arg.isInvalid())
1294 return true;
1295
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001296 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001297 return false;
1298}
1299
Chris Lattnerdc046542009-05-08 06:58:22 +00001300/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1301/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1302/// type of its first argument. The main ActOnCallExpr routines have already
1303/// promoted the types of arguments because all of these calls are prototyped as
1304/// void(...).
1305///
1306/// This function goes through and does final semantic checking for these
1307/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001308ExprResult
1309Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001310 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001311 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1312 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1313
1314 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001315 if (TheCall->getNumArgs() < 1) {
1316 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1317 << 0 << 1 << TheCall->getNumArgs()
1318 << TheCall->getCallee()->getSourceRange();
1319 return ExprError();
1320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattnerdc046542009-05-08 06:58:22 +00001322 // Inspect the first argument of the atomic builtin. This should always be
1323 // a pointer type, whose element is an integral scalar or pointer type.
1324 // Because it is a pointer type, we don't have to worry about any implicit
1325 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001326 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001327 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001328 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1329 if (FirstArgResult.isInvalid())
1330 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001331 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001332 TheCall->setArg(0, FirstArg);
1333
John McCall31168b02011-06-15 23:02:42 +00001334 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1335 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001336 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1337 << FirstArg->getType() << FirstArg->getSourceRange();
1338 return ExprError();
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
John McCall31168b02011-06-15 23:02:42 +00001341 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001342 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001343 !ValType->isBlockPointerType()) {
1344 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1345 << FirstArg->getType() << FirstArg->getSourceRange();
1346 return ExprError();
1347 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001348
John McCall31168b02011-06-15 23:02:42 +00001349 switch (ValType.getObjCLifetime()) {
1350 case Qualifiers::OCL_None:
1351 case Qualifiers::OCL_ExplicitNone:
1352 // okay
1353 break;
1354
1355 case Qualifiers::OCL_Weak:
1356 case Qualifiers::OCL_Strong:
1357 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001358 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001359 << ValType << FirstArg->getSourceRange();
1360 return ExprError();
1361 }
1362
John McCallb50451a2011-10-05 07:41:44 +00001363 // Strip any qualifiers off ValType.
1364 ValType = ValType.getUnqualifiedType();
1365
Chandler Carruth3973af72010-07-18 20:54:12 +00001366 // The majority of builtins return a value, but a few have special return
1367 // types, so allow them to override appropriately below.
1368 QualType ResultType = ValType;
1369
Chris Lattnerdc046542009-05-08 06:58:22 +00001370 // We need to figure out which concrete builtin this maps onto. For example,
1371 // __sync_fetch_and_add with a 2 byte object turns into
1372 // __sync_fetch_and_add_2.
1373#define BUILTIN_ROW(x) \
1374 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1375 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattnerdc046542009-05-08 06:58:22 +00001377 static const unsigned BuiltinIndices[][5] = {
1378 BUILTIN_ROW(__sync_fetch_and_add),
1379 BUILTIN_ROW(__sync_fetch_and_sub),
1380 BUILTIN_ROW(__sync_fetch_and_or),
1381 BUILTIN_ROW(__sync_fetch_and_and),
1382 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001383
Chris Lattnerdc046542009-05-08 06:58:22 +00001384 BUILTIN_ROW(__sync_add_and_fetch),
1385 BUILTIN_ROW(__sync_sub_and_fetch),
1386 BUILTIN_ROW(__sync_and_and_fetch),
1387 BUILTIN_ROW(__sync_or_and_fetch),
1388 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattnerdc046542009-05-08 06:58:22 +00001390 BUILTIN_ROW(__sync_val_compare_and_swap),
1391 BUILTIN_ROW(__sync_bool_compare_and_swap),
1392 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001393 BUILTIN_ROW(__sync_lock_release),
1394 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001395 };
Mike Stump11289f42009-09-09 15:08:12 +00001396#undef BUILTIN_ROW
1397
Chris Lattnerdc046542009-05-08 06:58:22 +00001398 // Determine the index of the size.
1399 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001400 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001401 case 1: SizeIndex = 0; break;
1402 case 2: SizeIndex = 1; break;
1403 case 4: SizeIndex = 2; break;
1404 case 8: SizeIndex = 3; break;
1405 case 16: SizeIndex = 4; break;
1406 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001407 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1408 << FirstArg->getType() << FirstArg->getSourceRange();
1409 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattnerdc046542009-05-08 06:58:22 +00001412 // Each of these builtins has one pointer argument, followed by some number of
1413 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1414 // that we ignore. Find out which row of BuiltinIndices to read from as well
1415 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001416 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001417 unsigned BuiltinIndex, NumFixed = 1;
1418 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001419 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001420 case Builtin::BI__sync_fetch_and_add:
1421 case Builtin::BI__sync_fetch_and_add_1:
1422 case Builtin::BI__sync_fetch_and_add_2:
1423 case Builtin::BI__sync_fetch_and_add_4:
1424 case Builtin::BI__sync_fetch_and_add_8:
1425 case Builtin::BI__sync_fetch_and_add_16:
1426 BuiltinIndex = 0;
1427 break;
1428
1429 case Builtin::BI__sync_fetch_and_sub:
1430 case Builtin::BI__sync_fetch_and_sub_1:
1431 case Builtin::BI__sync_fetch_and_sub_2:
1432 case Builtin::BI__sync_fetch_and_sub_4:
1433 case Builtin::BI__sync_fetch_and_sub_8:
1434 case Builtin::BI__sync_fetch_and_sub_16:
1435 BuiltinIndex = 1;
1436 break;
1437
1438 case Builtin::BI__sync_fetch_and_or:
1439 case Builtin::BI__sync_fetch_and_or_1:
1440 case Builtin::BI__sync_fetch_and_or_2:
1441 case Builtin::BI__sync_fetch_and_or_4:
1442 case Builtin::BI__sync_fetch_and_or_8:
1443 case Builtin::BI__sync_fetch_and_or_16:
1444 BuiltinIndex = 2;
1445 break;
1446
1447 case Builtin::BI__sync_fetch_and_and:
1448 case Builtin::BI__sync_fetch_and_and_1:
1449 case Builtin::BI__sync_fetch_and_and_2:
1450 case Builtin::BI__sync_fetch_and_and_4:
1451 case Builtin::BI__sync_fetch_and_and_8:
1452 case Builtin::BI__sync_fetch_and_and_16:
1453 BuiltinIndex = 3;
1454 break;
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor73722482011-11-28 16:30:08 +00001456 case Builtin::BI__sync_fetch_and_xor:
1457 case Builtin::BI__sync_fetch_and_xor_1:
1458 case Builtin::BI__sync_fetch_and_xor_2:
1459 case Builtin::BI__sync_fetch_and_xor_4:
1460 case Builtin::BI__sync_fetch_and_xor_8:
1461 case Builtin::BI__sync_fetch_and_xor_16:
1462 BuiltinIndex = 4;
1463 break;
1464
1465 case Builtin::BI__sync_add_and_fetch:
1466 case Builtin::BI__sync_add_and_fetch_1:
1467 case Builtin::BI__sync_add_and_fetch_2:
1468 case Builtin::BI__sync_add_and_fetch_4:
1469 case Builtin::BI__sync_add_and_fetch_8:
1470 case Builtin::BI__sync_add_and_fetch_16:
1471 BuiltinIndex = 5;
1472 break;
1473
1474 case Builtin::BI__sync_sub_and_fetch:
1475 case Builtin::BI__sync_sub_and_fetch_1:
1476 case Builtin::BI__sync_sub_and_fetch_2:
1477 case Builtin::BI__sync_sub_and_fetch_4:
1478 case Builtin::BI__sync_sub_and_fetch_8:
1479 case Builtin::BI__sync_sub_and_fetch_16:
1480 BuiltinIndex = 6;
1481 break;
1482
1483 case Builtin::BI__sync_and_and_fetch:
1484 case Builtin::BI__sync_and_and_fetch_1:
1485 case Builtin::BI__sync_and_and_fetch_2:
1486 case Builtin::BI__sync_and_and_fetch_4:
1487 case Builtin::BI__sync_and_and_fetch_8:
1488 case Builtin::BI__sync_and_and_fetch_16:
1489 BuiltinIndex = 7;
1490 break;
1491
1492 case Builtin::BI__sync_or_and_fetch:
1493 case Builtin::BI__sync_or_and_fetch_1:
1494 case Builtin::BI__sync_or_and_fetch_2:
1495 case Builtin::BI__sync_or_and_fetch_4:
1496 case Builtin::BI__sync_or_and_fetch_8:
1497 case Builtin::BI__sync_or_and_fetch_16:
1498 BuiltinIndex = 8;
1499 break;
1500
1501 case Builtin::BI__sync_xor_and_fetch:
1502 case Builtin::BI__sync_xor_and_fetch_1:
1503 case Builtin::BI__sync_xor_and_fetch_2:
1504 case Builtin::BI__sync_xor_and_fetch_4:
1505 case Builtin::BI__sync_xor_and_fetch_8:
1506 case Builtin::BI__sync_xor_and_fetch_16:
1507 BuiltinIndex = 9;
1508 break;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattnerdc046542009-05-08 06:58:22 +00001510 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001511 case Builtin::BI__sync_val_compare_and_swap_1:
1512 case Builtin::BI__sync_val_compare_and_swap_2:
1513 case Builtin::BI__sync_val_compare_and_swap_4:
1514 case Builtin::BI__sync_val_compare_and_swap_8:
1515 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001516 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001517 NumFixed = 2;
1518 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001519
Chris Lattnerdc046542009-05-08 06:58:22 +00001520 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001521 case Builtin::BI__sync_bool_compare_and_swap_1:
1522 case Builtin::BI__sync_bool_compare_and_swap_2:
1523 case Builtin::BI__sync_bool_compare_and_swap_4:
1524 case Builtin::BI__sync_bool_compare_and_swap_8:
1525 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001526 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001527 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001528 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001529 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001530
1531 case Builtin::BI__sync_lock_test_and_set:
1532 case Builtin::BI__sync_lock_test_and_set_1:
1533 case Builtin::BI__sync_lock_test_and_set_2:
1534 case Builtin::BI__sync_lock_test_and_set_4:
1535 case Builtin::BI__sync_lock_test_and_set_8:
1536 case Builtin::BI__sync_lock_test_and_set_16:
1537 BuiltinIndex = 12;
1538 break;
1539
Chris Lattnerdc046542009-05-08 06:58:22 +00001540 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001541 case Builtin::BI__sync_lock_release_1:
1542 case Builtin::BI__sync_lock_release_2:
1543 case Builtin::BI__sync_lock_release_4:
1544 case Builtin::BI__sync_lock_release_8:
1545 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001546 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001547 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001548 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001549 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001550
1551 case Builtin::BI__sync_swap:
1552 case Builtin::BI__sync_swap_1:
1553 case Builtin::BI__sync_swap_2:
1554 case Builtin::BI__sync_swap_4:
1555 case Builtin::BI__sync_swap_8:
1556 case Builtin::BI__sync_swap_16:
1557 BuiltinIndex = 14;
1558 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001559 }
Mike Stump11289f42009-09-09 15:08:12 +00001560
Chris Lattnerdc046542009-05-08 06:58:22 +00001561 // Now that we know how many fixed arguments we expect, first check that we
1562 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001563 if (TheCall->getNumArgs() < 1+NumFixed) {
1564 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1565 << 0 << 1+NumFixed << TheCall->getNumArgs()
1566 << TheCall->getCallee()->getSourceRange();
1567 return ExprError();
1568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Chris Lattner5b9241b2009-05-08 15:36:58 +00001570 // Get the decl for the concrete builtin from this, we can tell what the
1571 // concrete integer type we should convert to is.
1572 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1573 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001574 FunctionDecl *NewBuiltinDecl;
1575 if (NewBuiltinID == BuiltinID)
1576 NewBuiltinDecl = FDecl;
1577 else {
1578 // Perform builtin lookup to avoid redeclaring it.
1579 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1580 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1581 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1582 assert(Res.getFoundDecl());
1583 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001584 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001585 return ExprError();
1586 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001587
John McCallcf142162010-08-07 06:22:56 +00001588 // The first argument --- the pointer --- has a fixed type; we
1589 // deduce the types of the rest of the arguments accordingly. Walk
1590 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001591 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001592 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001593
Chris Lattnerdc046542009-05-08 06:58:22 +00001594 // GCC does an implicit conversion to the pointer or integer ValType. This
1595 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001596 // Initialize the argument.
1597 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1598 ValType, /*consume*/ false);
1599 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001600 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001601 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001602
Chris Lattnerdc046542009-05-08 06:58:22 +00001603 // Okay, we have something that *can* be converted to the right type. Check
1604 // to see if there is a potentially weird extension going on here. This can
1605 // happen when you do an atomic operation on something like an char* and
1606 // pass in 42. The 42 gets converted to char. This is even more strange
1607 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001608 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001609 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001612 ASTContext& Context = this->getASTContext();
1613
1614 // Create a new DeclRefExpr to refer to the new decl.
1615 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1616 Context,
1617 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001618 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001619 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001620 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001621 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001622 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001623 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattnerdc046542009-05-08 06:58:22 +00001625 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001626 // FIXME: This loses syntactic information.
1627 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1628 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1629 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001630 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001632 // Change the result type of the call to match the original value type. This
1633 // is arbitrary, but the codegen for these builtins ins design to handle it
1634 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001635 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001636
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001637 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001638}
1639
Chris Lattner6436fb62009-02-18 06:01:06 +00001640/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001641/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001642/// Note: It might also make sense to do the UTF-16 conversion here (would
1643/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001644bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001645 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001646 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1647
Douglas Gregorfb65e592011-07-27 05:40:30 +00001648 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001649 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1650 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001651 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001654 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001655 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001656 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001657 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001658 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001659 UTF16 *ToPtr = &ToBuf[0];
1660
1661 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1662 &ToPtr, ToPtr + NumBytes,
1663 strictConversion);
1664 // Check for conversion failure.
1665 if (Result != conversionOK)
1666 Diag(Arg->getLocStart(),
1667 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1668 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001669 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001670}
1671
Chris Lattnere202e6a2007-12-20 00:05:45 +00001672/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1673/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001674bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1675 Expr *Fn = TheCall->getCallee();
1676 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001677 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001678 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001679 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1680 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001681 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001682 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001683 return true;
1684 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001685
1686 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001687 return Diag(TheCall->getLocEnd(),
1688 diag::err_typecheck_call_too_few_args_at_least)
1689 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001690 }
1691
John McCall29ad95b2011-08-27 01:09:30 +00001692 // Type-check the first argument normally.
1693 if (checkBuiltinArgument(*this, TheCall, 0))
1694 return true;
1695
Chris Lattnere202e6a2007-12-20 00:05:45 +00001696 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001697 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001698 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001699 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001700 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001701 else if (FunctionDecl *FD = getCurFunctionDecl())
1702 isVariadic = FD->isVariadic();
1703 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001704 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattnere202e6a2007-12-20 00:05:45 +00001706 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001707 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1708 return true;
1709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
Chris Lattner43be2e62007-12-19 23:59:04 +00001711 // Verify that the second argument to the builtin is the last argument of the
1712 // current function or method.
1713 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001714 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001715
Nico Weber9eea7642013-05-24 23:31:57 +00001716 // These are valid if SecondArgIsLastNamedArgument is false after the next
1717 // block.
1718 QualType Type;
1719 SourceLocation ParamLoc;
1720
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001721 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1722 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001723 // FIXME: This isn't correct for methods (results in bogus warning).
1724 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001725 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001726 if (CurBlock)
1727 LastArg = *(CurBlock->TheDecl->param_end()-1);
1728 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001729 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001730 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001731 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001732 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001733
1734 Type = PV->getType();
1735 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001736 }
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Chris Lattner43be2e62007-12-19 23:59:04 +00001739 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001740 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001741 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001742 else if (Type->isReferenceType()) {
1743 Diag(Arg->getLocStart(),
1744 diag::warn_va_start_of_reference_type_is_undefined);
1745 Diag(ParamLoc, diag::note_parameter_type) << Type;
1746 }
1747
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001748 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001749 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001750}
Chris Lattner43be2e62007-12-19 23:59:04 +00001751
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001752bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1753 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1754 // const char *named_addr);
1755
1756 Expr *Func = Call->getCallee();
1757
1758 if (Call->getNumArgs() < 3)
1759 return Diag(Call->getLocEnd(),
1760 diag::err_typecheck_call_too_few_args_at_least)
1761 << 0 /*function call*/ << 3 << Call->getNumArgs();
1762
1763 // Determine whether the current function is variadic or not.
1764 bool IsVariadic;
1765 if (BlockScopeInfo *CurBlock = getCurBlock())
1766 IsVariadic = CurBlock->TheDecl->isVariadic();
1767 else if (FunctionDecl *FD = getCurFunctionDecl())
1768 IsVariadic = FD->isVariadic();
1769 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1770 IsVariadic = MD->isVariadic();
1771 else
1772 llvm_unreachable("unexpected statement type");
1773
1774 if (!IsVariadic) {
1775 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1776 return true;
1777 }
1778
1779 // Type-check the first argument normally.
1780 if (checkBuiltinArgument(*this, Call, 0))
1781 return true;
1782
1783 static const struct {
1784 unsigned ArgNo;
1785 QualType Type;
1786 } ArgumentTypes[] = {
1787 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1788 { 2, Context.getSizeType() },
1789 };
1790
1791 for (const auto &AT : ArgumentTypes) {
1792 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1793 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1794 continue;
1795 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1796 << Arg->getType() << AT.Type << 1 /* different class */
1797 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1798 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1799 }
1800
1801 return false;
1802}
1803
Chris Lattner2da14fb2007-12-20 00:26:33 +00001804/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1805/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001806bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1807 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001808 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001809 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001810 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001811 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001812 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001813 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001814 << SourceRange(TheCall->getArg(2)->getLocStart(),
1815 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001816
John Wiegley01296292011-04-08 18:41:53 +00001817 ExprResult OrigArg0 = TheCall->getArg(0);
1818 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001819
Chris Lattner2da14fb2007-12-20 00:26:33 +00001820 // Do standard promotions between the two arguments, returning their common
1821 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001822 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001823 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1824 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001825
1826 // Make sure any conversions are pushed back into the call; this is
1827 // type safe since unordered compare builtins are declared as "_Bool
1828 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001829 TheCall->setArg(0, OrigArg0.get());
1830 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001831
John Wiegley01296292011-04-08 18:41:53 +00001832 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001833 return false;
1834
Chris Lattner2da14fb2007-12-20 00:26:33 +00001835 // If the common type isn't a real floating type, then the arguments were
1836 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001837 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001838 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001839 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001840 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1841 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001842
Chris Lattner2da14fb2007-12-20 00:26:33 +00001843 return false;
1844}
1845
Benjamin Kramer634fc102010-02-15 22:42:31 +00001846/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1847/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001848/// to check everything. We expect the last argument to be a floating point
1849/// value.
1850bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1851 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001852 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001853 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001854 if (TheCall->getNumArgs() > NumArgs)
1855 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001856 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001857 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001858 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001859 (*(TheCall->arg_end()-1))->getLocEnd());
1860
Benjamin Kramer64aae502010-02-16 10:07:31 +00001861 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Eli Friedman7e4faac2009-08-31 20:06:00 +00001863 if (OrigArg->isTypeDependent())
1864 return false;
1865
Chris Lattner68784ef2010-05-06 05:50:07 +00001866 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001867 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001868 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001869 diag::err_typecheck_call_invalid_unary_fp)
1870 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001871
Chris Lattner68784ef2010-05-06 05:50:07 +00001872 // If this is an implicit conversion from float -> double, remove it.
1873 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1874 Expr *CastArg = Cast->getSubExpr();
1875 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1876 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1877 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001878 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001879 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001880 }
1881 }
1882
Eli Friedman7e4faac2009-08-31 20:06:00 +00001883 return false;
1884}
1885
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001886/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1887// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001888ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001889 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001890 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001891 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001892 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1893 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001894
Nate Begemana0110022010-06-08 00:16:34 +00001895 // Determine which of the following types of shufflevector we're checking:
1896 // 1) unary, vector mask: (lhs, mask)
1897 // 2) binary, vector mask: (lhs, rhs, mask)
1898 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1899 QualType resType = TheCall->getArg(0)->getType();
1900 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001901
Douglas Gregorc25f7662009-05-19 22:10:17 +00001902 if (!TheCall->getArg(0)->isTypeDependent() &&
1903 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001904 QualType LHSType = TheCall->getArg(0)->getType();
1905 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001906
Craig Topperbaca3892013-07-29 06:47:04 +00001907 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1908 return ExprError(Diag(TheCall->getLocStart(),
1909 diag::err_shufflevector_non_vector)
1910 << SourceRange(TheCall->getArg(0)->getLocStart(),
1911 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001912
Nate Begemana0110022010-06-08 00:16:34 +00001913 numElements = LHSType->getAs<VectorType>()->getNumElements();
1914 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001915
Nate Begemana0110022010-06-08 00:16:34 +00001916 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1917 // with mask. If so, verify that RHS is an integer vector type with the
1918 // same number of elts as lhs.
1919 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001920 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001921 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001922 return ExprError(Diag(TheCall->getLocStart(),
1923 diag::err_shufflevector_incompatible_vector)
1924 << SourceRange(TheCall->getArg(1)->getLocStart(),
1925 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001926 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001927 return ExprError(Diag(TheCall->getLocStart(),
1928 diag::err_shufflevector_incompatible_vector)
1929 << SourceRange(TheCall->getArg(0)->getLocStart(),
1930 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001931 } else if (numElements != numResElements) {
1932 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001933 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001934 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001935 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001936 }
1937
1938 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001939 if (TheCall->getArg(i)->isTypeDependent() ||
1940 TheCall->getArg(i)->isValueDependent())
1941 continue;
1942
Nate Begemana0110022010-06-08 00:16:34 +00001943 llvm::APSInt Result(32);
1944 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1945 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001946 diag::err_shufflevector_nonconstant_argument)
1947 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001948
Craig Topper50ad5b72013-08-03 17:40:38 +00001949 // Allow -1 which will be translated to undef in the IR.
1950 if (Result.isSigned() && Result.isAllOnesValue())
1951 continue;
1952
Chris Lattner7ab824e2008-08-10 02:05:13 +00001953 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001954 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001955 diag::err_shufflevector_argument_too_large)
1956 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001957 }
1958
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001959 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001960
Chris Lattner7ab824e2008-08-10 02:05:13 +00001961 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001962 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001963 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001964 }
1965
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001966 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1967 TheCall->getCallee()->getLocStart(),
1968 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001969}
Chris Lattner43be2e62007-12-19 23:59:04 +00001970
Hal Finkelc4d7c822013-09-18 03:29:45 +00001971/// SemaConvertVectorExpr - Handle __builtin_convertvector
1972ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1973 SourceLocation BuiltinLoc,
1974 SourceLocation RParenLoc) {
1975 ExprValueKind VK = VK_RValue;
1976 ExprObjectKind OK = OK_Ordinary;
1977 QualType DstTy = TInfo->getType();
1978 QualType SrcTy = E->getType();
1979
1980 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1981 return ExprError(Diag(BuiltinLoc,
1982 diag::err_convertvector_non_vector)
1983 << E->getSourceRange());
1984 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1985 return ExprError(Diag(BuiltinLoc,
1986 diag::err_convertvector_non_vector_type));
1987
1988 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1989 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1990 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1991 if (SrcElts != DstElts)
1992 return ExprError(Diag(BuiltinLoc,
1993 diag::err_convertvector_incompatible_vector)
1994 << E->getSourceRange());
1995 }
1996
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001997 return new (Context)
1998 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001999}
2000
Daniel Dunbarb7257262008-07-21 22:59:13 +00002001/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2002// This is declared to take (const void*, ...) and can take two
2003// optional constant int args.
2004bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002005 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002006
Chris Lattner3b054132008-11-19 05:08:23 +00002007 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002008 return Diag(TheCall->getLocEnd(),
2009 diag::err_typecheck_call_too_many_args_at_most)
2010 << 0 /*function call*/ << 3 << NumArgs
2011 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002012
2013 // Argument 0 is checked for us and the remaining arguments must be
2014 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002015 for (unsigned i = 1; i != NumArgs; ++i)
2016 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002017 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002018
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002019 return false;
2020}
2021
Hal Finkelf0417332014-07-17 14:25:55 +00002022/// SemaBuiltinAssume - Handle __assume (MS Extension).
2023// __assume does not evaluate its arguments, and should warn if its argument
2024// has side effects.
2025bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2026 Expr *Arg = TheCall->getArg(0);
2027 if (Arg->isInstantiationDependent()) return false;
2028
2029 if (Arg->HasSideEffects(Context))
2030 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2031 << Arg->getSourceRange();
2032
2033 return false;
2034}
2035
Eric Christopher8d0c6212010-04-17 02:26:23 +00002036/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2037/// TheCall is a constant expression.
2038bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2039 llvm::APSInt &Result) {
2040 Expr *Arg = TheCall->getArg(ArgNum);
2041 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2042 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2043
2044 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2045
2046 if (!Arg->isIntegerConstantExpr(Result, Context))
2047 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002048 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002049
Chris Lattnerd545ad12009-09-23 06:06:36 +00002050 return false;
2051}
2052
Richard Sandiford28940af2014-04-16 08:47:51 +00002053/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2054/// TheCall is a constant expression in the range [Low, High].
2055bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2056 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002057 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002058
2059 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002060 Expr *Arg = TheCall->getArg(ArgNum);
2061 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002062 return false;
2063
Eric Christopher8d0c6212010-04-17 02:26:23 +00002064 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002065 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002066 return true;
2067
Richard Sandiford28940af2014-04-16 08:47:51 +00002068 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002069 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002070 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002071
2072 return false;
2073}
2074
Eli Friedmanc97d0142009-05-03 06:04:26 +00002075/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002076/// This checks that val is a constant 1.
2077bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2078 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002079 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002080
Eric Christopher8d0c6212010-04-17 02:26:23 +00002081 // TODO: This is less than ideal. Overload this to take a value.
2082 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2083 return true;
2084
2085 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002086 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2087 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2088
2089 return false;
2090}
2091
Richard Smithd7293d72013-08-05 18:49:43 +00002092namespace {
2093enum StringLiteralCheckType {
2094 SLCT_NotALiteral,
2095 SLCT_UncheckedLiteral,
2096 SLCT_CheckedLiteral
2097};
2098}
2099
Richard Smith55ce3522012-06-25 20:30:08 +00002100// Determine if an expression is a string literal or constant string.
2101// If this function returns false on the arguments to a function expecting a
2102// format string, we will usually need to emit a warning.
2103// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002104static StringLiteralCheckType
2105checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2106 bool HasVAListArg, unsigned format_idx,
2107 unsigned firstDataArg, Sema::FormatStringType Type,
2108 Sema::VariadicCallType CallType, bool InFunctionCall,
2109 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002110 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002111 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002112 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002113
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002114 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002115
Richard Smithd7293d72013-08-05 18:49:43 +00002116 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002117 // Technically -Wformat-nonliteral does not warn about this case.
2118 // The behavior of printf and friends in this case is implementation
2119 // dependent. Ideally if the format string cannot be null then
2120 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002121 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002122
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002123 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002124 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002125 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002126 // The expression is a literal if both sub-expressions were, and it was
2127 // completely checked only if both sub-expressions were checked.
2128 const AbstractConditionalOperator *C =
2129 cast<AbstractConditionalOperator>(E);
2130 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002131 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002132 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002133 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002134 if (Left == SLCT_NotALiteral)
2135 return SLCT_NotALiteral;
2136 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002137 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002138 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002139 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002140 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002141 }
2142
2143 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002144 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2145 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002146 }
2147
John McCallc07a0c72011-02-17 10:25:35 +00002148 case Stmt::OpaqueValueExprClass:
2149 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2150 E = src;
2151 goto tryAgain;
2152 }
Richard Smith55ce3522012-06-25 20:30:08 +00002153 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002154
Ted Kremeneka8890832011-02-24 23:03:04 +00002155 case Stmt::PredefinedExprClass:
2156 // While __func__, etc., are technically not string literals, they
2157 // cannot contain format specifiers and thus are not a security
2158 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002159 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002160
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002161 case Stmt::DeclRefExprClass: {
2162 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 // As an exception, do not flag errors for variables binding to
2165 // const string literals.
2166 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2167 bool isConstant = false;
2168 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002169
Richard Smithd7293d72013-08-05 18:49:43 +00002170 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2171 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002172 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002173 isConstant = T.isConstant(S.Context) &&
2174 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002175 } else if (T->isObjCObjectPointerType()) {
2176 // In ObjC, there is usually no "const ObjectPointer" type,
2177 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002178 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002181 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002182 if (const Expr *Init = VD->getAnyInitializer()) {
2183 // Look through initializers like const char c[] = { "foo" }
2184 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2185 if (InitList->isStringLiteralInit())
2186 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2187 }
Richard Smithd7293d72013-08-05 18:49:43 +00002188 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002189 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002190 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002191 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002192 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002193 }
Mike Stump11289f42009-09-09 15:08:12 +00002194
Anders Carlssonb012ca92009-06-28 19:55:58 +00002195 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2196 // special check to see if the format string is a function parameter
2197 // of the function calling the printf function. If the function
2198 // has an attribute indicating it is a printf-like function, then we
2199 // should suppress warnings concerning non-literals being used in a call
2200 // to a vprintf function. For example:
2201 //
2202 // void
2203 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2204 // va_list ap;
2205 // va_start(ap, fmt);
2206 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2207 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002208 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002209 if (HasVAListArg) {
2210 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2211 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2212 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002213 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002214 // adjust for implicit parameter
2215 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2216 if (MD->isInstance())
2217 ++PVIndex;
2218 // We also check if the formats are compatible.
2219 // We can't pass a 'scanf' string to a 'printf' function.
2220 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002221 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002222 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002223 }
2224 }
2225 }
2226 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002227 }
Mike Stump11289f42009-09-09 15:08:12 +00002228
Richard Smith55ce3522012-06-25 20:30:08 +00002229 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002230 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002231
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002232 case Stmt::CallExprClass:
2233 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002234 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002235 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2236 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2237 unsigned ArgIndex = FA->getFormatIdx();
2238 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2239 if (MD->isInstance())
2240 --ArgIndex;
2241 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Richard Smithd7293d72013-08-05 18:49:43 +00002243 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002244 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002245 Type, CallType, InFunctionCall,
2246 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002247 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2248 unsigned BuiltinID = FD->getBuiltinID();
2249 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2250 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2251 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002252 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002253 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002254 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002255 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002256 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002257 }
2258 }
Mike Stump11289f42009-09-09 15:08:12 +00002259
Richard Smith55ce3522012-06-25 20:30:08 +00002260 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002261 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002262 case Stmt::ObjCStringLiteralClass:
2263 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002264 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002265
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002266 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002267 StrE = ObjCFExpr->getString();
2268 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002269 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002271 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002272 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2273 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002274 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002275 }
Mike Stump11289f42009-09-09 15:08:12 +00002276
Richard Smith55ce3522012-06-25 20:30:08 +00002277 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002280 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002281 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002282 }
2283}
2284
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002285Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002286 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002287 .Case("scanf", FST_Scanf)
2288 .Cases("printf", "printf0", FST_Printf)
2289 .Cases("NSString", "CFString", FST_NSString)
2290 .Case("strftime", FST_Strftime)
2291 .Case("strfmon", FST_Strfmon)
2292 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2293 .Default(FST_Unknown);
2294}
2295
Jordan Rose3e0ec582012-07-19 18:10:23 +00002296/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002297/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002298/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002299bool Sema::CheckFormatArguments(const FormatAttr *Format,
2300 ArrayRef<const Expr *> Args,
2301 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002302 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002303 SourceLocation Loc, SourceRange Range,
2304 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002305 FormatStringInfo FSI;
2306 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002307 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002308 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002309 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002310 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002311}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002312
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002313bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002314 bool HasVAListArg, unsigned format_idx,
2315 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002316 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002317 SourceLocation Loc, SourceRange Range,
2318 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002319 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002320 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002321 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002322 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002323 }
Mike Stump11289f42009-09-09 15:08:12 +00002324
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002325 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002327 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002328 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002329 // Dynamically generated format strings are difficult to
2330 // automatically vet at compile time. Requiring that format strings
2331 // are string literals: (1) permits the checking of format strings by
2332 // the compiler and thereby (2) can practically remove the source of
2333 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002334
Mike Stump11289f42009-09-09 15:08:12 +00002335 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002336 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002337 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002338 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002339 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002340 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2341 format_idx, firstDataArg, Type, CallType,
2342 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002343 if (CT != SLCT_NotALiteral)
2344 // Literal format string found, check done!
2345 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002346
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002347 // Strftime is particular as it always uses a single 'time' argument,
2348 // so it is safe to pass a non-literal string.
2349 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002350 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002351
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002352 // Do not emit diag when the string param is a macro expansion and the
2353 // format is either NSString or CFString. This is a hack to prevent
2354 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2355 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002356 if (Type == FST_NSString &&
2357 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002358 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002359
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002360 // If there are no arguments specified, warn with -Wformat-security, otherwise
2361 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002362 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002363 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002364 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002365 << OrigFormatExpr->getSourceRange();
2366 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002367 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002368 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002369 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002370 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002371}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002372
Ted Kremenekab278de2010-01-28 23:39:18 +00002373namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002374class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2375protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002376 Sema &S;
2377 const StringLiteral *FExpr;
2378 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002379 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002380 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002381 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002382 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002383 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002384 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002385 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002386 bool usesPositionalArgs;
2387 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002388 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002389 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002390 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002391public:
Ted Kremenek02087932010-07-16 02:11:22 +00002392 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002393 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002394 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002395 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002396 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002397 Sema::VariadicCallType callType,
2398 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002399 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002400 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2401 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002402 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002403 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002404 inFunctionCall(inFunctionCall), CallType(callType),
2405 CheckedVarArgs(CheckedVarArgs) {
2406 CoveredArgs.resize(numDataArgs);
2407 CoveredArgs.reset();
2408 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002409
Ted Kremenek019d2242010-01-29 01:50:07 +00002410 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002411
Ted Kremenek02087932010-07-16 02:11:22 +00002412 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002413 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002414
Jordan Rose92303592012-09-08 04:00:03 +00002415 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002416 const analyze_format_string::FormatSpecifier &FS,
2417 const analyze_format_string::ConversionSpecifier &CS,
2418 const char *startSpecifier, unsigned specifierLen,
2419 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002420
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002421 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002422 const analyze_format_string::FormatSpecifier &FS,
2423 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002424
2425 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002426 const analyze_format_string::ConversionSpecifier &CS,
2427 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002428
Craig Toppere14c0f82014-03-12 04:55:44 +00002429 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002430
Craig Toppere14c0f82014-03-12 04:55:44 +00002431 void HandleInvalidPosition(const char *startSpecifier,
2432 unsigned specifierLen,
2433 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002434
Craig Toppere14c0f82014-03-12 04:55:44 +00002435 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002436
Craig Toppere14c0f82014-03-12 04:55:44 +00002437 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002438
Richard Trieu03cf7b72011-10-28 00:41:25 +00002439 template <typename Range>
2440 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2441 const Expr *ArgumentExpr,
2442 PartialDiagnostic PDiag,
2443 SourceLocation StringLoc,
2444 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002445 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002446
Ted Kremenek02087932010-07-16 02:11:22 +00002447protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002448 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2449 const char *startSpec,
2450 unsigned specifierLen,
2451 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002452
2453 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2454 const char *startSpec,
2455 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002456
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002457 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002458 CharSourceRange getSpecifierRange(const char *startSpecifier,
2459 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002460 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002461
Ted Kremenek5739de72010-01-29 01:06:55 +00002462 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002463
2464 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2465 const analyze_format_string::ConversionSpecifier &CS,
2466 const char *startSpecifier, unsigned specifierLen,
2467 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002468
2469 template <typename Range>
2470 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2471 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002472 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002473};
2474}
2475
Ted Kremenek02087932010-07-16 02:11:22 +00002476SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002477 return OrigFormatExpr->getSourceRange();
2478}
2479
Ted Kremenek02087932010-07-16 02:11:22 +00002480CharSourceRange CheckFormatHandler::
2481getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002482 SourceLocation Start = getLocationOfByte(startSpecifier);
2483 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2484
2485 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002486 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002487
2488 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002489}
2490
Ted Kremenek02087932010-07-16 02:11:22 +00002491SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002492 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002493}
2494
Ted Kremenek02087932010-07-16 02:11:22 +00002495void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2496 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002497 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2498 getLocationOfByte(startSpecifier),
2499 /*IsStringLocation*/true,
2500 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002501}
2502
Jordan Rose92303592012-09-08 04:00:03 +00002503void CheckFormatHandler::HandleInvalidLengthModifier(
2504 const analyze_format_string::FormatSpecifier &FS,
2505 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002506 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002507 using namespace analyze_format_string;
2508
2509 const LengthModifier &LM = FS.getLengthModifier();
2510 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2511
2512 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002513 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002514 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002515 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002516 getLocationOfByte(LM.getStart()),
2517 /*IsStringLocation*/true,
2518 getSpecifierRange(startSpecifier, specifierLen));
2519
2520 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2521 << FixedLM->toString()
2522 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2523
2524 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002525 FixItHint Hint;
2526 if (DiagID == diag::warn_format_nonsensical_length)
2527 Hint = FixItHint::CreateRemoval(LMRange);
2528
2529 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002530 getLocationOfByte(LM.getStart()),
2531 /*IsStringLocation*/true,
2532 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002533 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002534 }
2535}
2536
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002537void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002538 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002539 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002540 using namespace analyze_format_string;
2541
2542 const LengthModifier &LM = FS.getLengthModifier();
2543 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2544
2545 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002546 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002547 if (FixedLM) {
2548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2549 << LM.toString() << 0,
2550 getLocationOfByte(LM.getStart()),
2551 /*IsStringLocation*/true,
2552 getSpecifierRange(startSpecifier, specifierLen));
2553
2554 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2555 << FixedLM->toString()
2556 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2557
2558 } else {
2559 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2560 << LM.toString() << 0,
2561 getLocationOfByte(LM.getStart()),
2562 /*IsStringLocation*/true,
2563 getSpecifierRange(startSpecifier, specifierLen));
2564 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002565}
2566
2567void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2568 const analyze_format_string::ConversionSpecifier &CS,
2569 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002570 using namespace analyze_format_string;
2571
2572 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002573 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002574 if (FixedCS) {
2575 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2576 << CS.toString() << /*conversion specifier*/1,
2577 getLocationOfByte(CS.getStart()),
2578 /*IsStringLocation*/true,
2579 getSpecifierRange(startSpecifier, specifierLen));
2580
2581 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2582 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2583 << FixedCS->toString()
2584 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2585 } else {
2586 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2587 << CS.toString() << /*conversion specifier*/1,
2588 getLocationOfByte(CS.getStart()),
2589 /*IsStringLocation*/true,
2590 getSpecifierRange(startSpecifier, specifierLen));
2591 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002592}
2593
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002594void CheckFormatHandler::HandlePosition(const char *startPos,
2595 unsigned posLen) {
2596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2597 getLocationOfByte(startPos),
2598 /*IsStringLocation*/true,
2599 getSpecifierRange(startPos, posLen));
2600}
2601
Ted Kremenekd1668192010-02-27 01:41:03 +00002602void
Ted Kremenek02087932010-07-16 02:11:22 +00002603CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2604 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002605 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2606 << (unsigned) p,
2607 getLocationOfByte(startPos), /*IsStringLocation*/true,
2608 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002609}
2610
Ted Kremenek02087932010-07-16 02:11:22 +00002611void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002612 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002613 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2614 getLocationOfByte(startPos),
2615 /*IsStringLocation*/true,
2616 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002617}
2618
Ted Kremenek02087932010-07-16 02:11:22 +00002619void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002620 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002621 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002622 EmitFormatDiagnostic(
2623 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2624 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2625 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002626 }
Ted Kremenek02087932010-07-16 02:11:22 +00002627}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002628
Jordan Rose58bbe422012-07-19 18:10:08 +00002629// Note that this may return NULL if there was an error parsing or building
2630// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002631const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002632 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002633}
2634
2635void CheckFormatHandler::DoneProcessing() {
2636 // Does the number of data arguments exceed the number of
2637 // format conversions in the format string?
2638 if (!HasVAListArg) {
2639 // Find any arguments that weren't covered.
2640 CoveredArgs.flip();
2641 signed notCoveredArg = CoveredArgs.find_first();
2642 if (notCoveredArg >= 0) {
2643 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002644 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2645 SourceLocation Loc = E->getLocStart();
2646 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2647 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2648 Loc, /*IsStringLocation*/false,
2649 getFormatStringRange());
2650 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002651 }
Ted Kremenek02087932010-07-16 02:11:22 +00002652 }
2653 }
2654}
2655
Ted Kremenekce815422010-07-19 21:25:57 +00002656bool
2657CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2658 SourceLocation Loc,
2659 const char *startSpec,
2660 unsigned specifierLen,
2661 const char *csStart,
2662 unsigned csLen) {
2663
2664 bool keepGoing = true;
2665 if (argIndex < NumDataArgs) {
2666 // Consider the argument coverered, even though the specifier doesn't
2667 // make sense.
2668 CoveredArgs.set(argIndex);
2669 }
2670 else {
2671 // If argIndex exceeds the number of data arguments we
2672 // don't issue a warning because that is just a cascade of warnings (and
2673 // they may have intended '%%' anyway). We don't want to continue processing
2674 // the format string after this point, however, as we will like just get
2675 // gibberish when trying to match arguments.
2676 keepGoing = false;
2677 }
2678
Richard Trieu03cf7b72011-10-28 00:41:25 +00002679 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2680 << StringRef(csStart, csLen),
2681 Loc, /*IsStringLocation*/true,
2682 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002683
2684 return keepGoing;
2685}
2686
Richard Trieu03cf7b72011-10-28 00:41:25 +00002687void
2688CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2689 const char *startSpec,
2690 unsigned specifierLen) {
2691 EmitFormatDiagnostic(
2692 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2693 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2694}
2695
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002696bool
2697CheckFormatHandler::CheckNumArgs(
2698 const analyze_format_string::FormatSpecifier &FS,
2699 const analyze_format_string::ConversionSpecifier &CS,
2700 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2701
2702 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002703 PartialDiagnostic PDiag = FS.usesPositionalArg()
2704 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2705 << (argIndex+1) << NumDataArgs)
2706 : S.PDiag(diag::warn_printf_insufficient_data_args);
2707 EmitFormatDiagnostic(
2708 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2709 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002710 return false;
2711 }
2712 return true;
2713}
2714
Richard Trieu03cf7b72011-10-28 00:41:25 +00002715template<typename Range>
2716void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2717 SourceLocation Loc,
2718 bool IsStringLocation,
2719 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002720 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002721 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002722 Loc, IsStringLocation, StringRange, FixIt);
2723}
2724
2725/// \brief If the format string is not within the funcion call, emit a note
2726/// so that the function call and string are in diagnostic messages.
2727///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002728/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002729/// call and only one diagnostic message will be produced. Otherwise, an
2730/// extra note will be emitted pointing to location of the format string.
2731///
2732/// \param ArgumentExpr the expression that is passed as the format string
2733/// argument in the function call. Used for getting locations when two
2734/// diagnostics are emitted.
2735///
2736/// \param PDiag the callee should already have provided any strings for the
2737/// diagnostic message. This function only adds locations and fixits
2738/// to diagnostics.
2739///
2740/// \param Loc primary location for diagnostic. If two diagnostics are
2741/// required, one will be at Loc and a new SourceLocation will be created for
2742/// the other one.
2743///
2744/// \param IsStringLocation if true, Loc points to the format string should be
2745/// used for the note. Otherwise, Loc points to the argument list and will
2746/// be used with PDiag.
2747///
2748/// \param StringRange some or all of the string to highlight. This is
2749/// templated so it can accept either a CharSourceRange or a SourceRange.
2750///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002751/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002752template<typename Range>
2753void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2754 const Expr *ArgumentExpr,
2755 PartialDiagnostic PDiag,
2756 SourceLocation Loc,
2757 bool IsStringLocation,
2758 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002759 ArrayRef<FixItHint> FixIt) {
2760 if (InFunctionCall) {
2761 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2762 D << StringRange;
2763 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2764 I != E; ++I) {
2765 D << *I;
2766 }
2767 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002768 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2769 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002770
2771 const Sema::SemaDiagnosticBuilder &Note =
2772 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2773 diag::note_format_string_defined);
2774
2775 Note << StringRange;
2776 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2777 I != E; ++I) {
2778 Note << *I;
2779 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002780 }
2781}
2782
Ted Kremenek02087932010-07-16 02:11:22 +00002783//===--- CHECK: Printf format string checking ------------------------------===//
2784
2785namespace {
2786class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002787 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002788public:
2789 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2790 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002791 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002792 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002793 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002794 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002795 Sema::VariadicCallType CallType,
2796 llvm::SmallBitVector &CheckedVarArgs)
2797 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2798 numDataArgs, beg, hasVAListArg, Args,
2799 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2800 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002801 {}
2802
Craig Toppere14c0f82014-03-12 04:55:44 +00002803
Ted Kremenek02087932010-07-16 02:11:22 +00002804 bool HandleInvalidPrintfConversionSpecifier(
2805 const analyze_printf::PrintfSpecifier &FS,
2806 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002807 unsigned specifierLen) override;
2808
Ted Kremenek02087932010-07-16 02:11:22 +00002809 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2810 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002811 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002812 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2813 const char *StartSpecifier,
2814 unsigned SpecifierLen,
2815 const Expr *E);
2816
Ted Kremenek02087932010-07-16 02:11:22 +00002817 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2818 const char *startSpecifier, unsigned specifierLen);
2819 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2820 const analyze_printf::OptionalAmount &Amt,
2821 unsigned type,
2822 const char *startSpecifier, unsigned specifierLen);
2823 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2824 const analyze_printf::OptionalFlag &flag,
2825 const char *startSpecifier, unsigned specifierLen);
2826 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2827 const analyze_printf::OptionalFlag &ignoredFlag,
2828 const analyze_printf::OptionalFlag &flag,
2829 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002830 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002831 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002832
Ted Kremenek02087932010-07-16 02:11:22 +00002833};
2834}
2835
2836bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2837 const analyze_printf::PrintfSpecifier &FS,
2838 const char *startSpecifier,
2839 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002840 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002841 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002842
Ted Kremenekce815422010-07-19 21:25:57 +00002843 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2844 getLocationOfByte(CS.getStart()),
2845 startSpecifier, specifierLen,
2846 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002847}
2848
Ted Kremenek02087932010-07-16 02:11:22 +00002849bool CheckPrintfHandler::HandleAmount(
2850 const analyze_format_string::OptionalAmount &Amt,
2851 unsigned k, const char *startSpecifier,
2852 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002853
2854 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002855 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002856 unsigned argIndex = Amt.getArgIndex();
2857 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002858 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2859 << k,
2860 getLocationOfByte(Amt.getStart()),
2861 /*IsStringLocation*/true,
2862 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002863 // Don't do any more checking. We will just emit
2864 // spurious errors.
2865 return false;
2866 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002867
Ted Kremenek5739de72010-01-29 01:06:55 +00002868 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002869 // Although not in conformance with C99, we also allow the argument to be
2870 // an 'unsigned int' as that is a reasonably safe case. GCC also
2871 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002872 CoveredArgs.set(argIndex);
2873 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002874 if (!Arg)
2875 return false;
2876
Ted Kremenek5739de72010-01-29 01:06:55 +00002877 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002878
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002879 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2880 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002881
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002882 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002883 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002884 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002885 << T << Arg->getSourceRange(),
2886 getLocationOfByte(Amt.getStart()),
2887 /*IsStringLocation*/true,
2888 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002889 // Don't do any more checking. We will just emit
2890 // spurious errors.
2891 return false;
2892 }
2893 }
2894 }
2895 return true;
2896}
Ted Kremenek5739de72010-01-29 01:06:55 +00002897
Tom Careb49ec692010-06-17 19:00:27 +00002898void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002899 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002900 const analyze_printf::OptionalAmount &Amt,
2901 unsigned type,
2902 const char *startSpecifier,
2903 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002904 const analyze_printf::PrintfConversionSpecifier &CS =
2905 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002906
Richard Trieu03cf7b72011-10-28 00:41:25 +00002907 FixItHint fixit =
2908 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2909 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2910 Amt.getConstantLength()))
2911 : FixItHint();
2912
2913 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2914 << type << CS.toString(),
2915 getLocationOfByte(Amt.getStart()),
2916 /*IsStringLocation*/true,
2917 getSpecifierRange(startSpecifier, specifierLen),
2918 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002919}
2920
Ted Kremenek02087932010-07-16 02:11:22 +00002921void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002922 const analyze_printf::OptionalFlag &flag,
2923 const char *startSpecifier,
2924 unsigned specifierLen) {
2925 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002926 const analyze_printf::PrintfConversionSpecifier &CS =
2927 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002928 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2929 << flag.toString() << CS.toString(),
2930 getLocationOfByte(flag.getPosition()),
2931 /*IsStringLocation*/true,
2932 getSpecifierRange(startSpecifier, specifierLen),
2933 FixItHint::CreateRemoval(
2934 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002935}
2936
2937void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002938 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002939 const analyze_printf::OptionalFlag &ignoredFlag,
2940 const analyze_printf::OptionalFlag &flag,
2941 const char *startSpecifier,
2942 unsigned specifierLen) {
2943 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002944 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2945 << ignoredFlag.toString() << flag.toString(),
2946 getLocationOfByte(ignoredFlag.getPosition()),
2947 /*IsStringLocation*/true,
2948 getSpecifierRange(startSpecifier, specifierLen),
2949 FixItHint::CreateRemoval(
2950 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002951}
2952
Richard Smith55ce3522012-06-25 20:30:08 +00002953// Determines if the specified is a C++ class or struct containing
2954// a member with the specified name and kind (e.g. a CXXMethodDecl named
2955// "c_str()").
2956template<typename MemberKind>
2957static llvm::SmallPtrSet<MemberKind*, 1>
2958CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2959 const RecordType *RT = Ty->getAs<RecordType>();
2960 llvm::SmallPtrSet<MemberKind*, 1> Results;
2961
2962 if (!RT)
2963 return Results;
2964 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002965 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002966 return Results;
2967
Alp Tokerb6cc5922014-05-03 03:45:55 +00002968 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002969 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002970 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002971
2972 // We just need to include all members of the right kind turned up by the
2973 // filter, at this point.
2974 if (S.LookupQualifiedName(R, RT->getDecl()))
2975 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2976 NamedDecl *decl = (*I)->getUnderlyingDecl();
2977 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2978 Results.insert(FK);
2979 }
2980 return Results;
2981}
2982
Richard Smith2868a732014-02-28 01:36:39 +00002983/// Check if we could call '.c_str()' on an object.
2984///
2985/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2986/// allow the call, or if it would be ambiguous).
2987bool Sema::hasCStrMethod(const Expr *E) {
2988 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2989 MethodSet Results =
2990 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2991 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2992 MI != ME; ++MI)
2993 if ((*MI)->getMinRequiredArguments() == 0)
2994 return true;
2995 return false;
2996}
2997
Richard Smith55ce3522012-06-25 20:30:08 +00002998// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002999// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003000// Returns true when a c_str() conversion method is found.
3001bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003002 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003003 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3004
3005 MethodSet Results =
3006 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3007
3008 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3009 MI != ME; ++MI) {
3010 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003011 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003012 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003013 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003014 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003015 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3016 << "c_str()"
3017 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3018 return true;
3019 }
3020 }
3021
3022 return false;
3023}
3024
Ted Kremenekab278de2010-01-28 23:39:18 +00003025bool
Ted Kremenek02087932010-07-16 02:11:22 +00003026CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003027 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003028 const char *startSpecifier,
3029 unsigned specifierLen) {
3030
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003031 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003032 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003033 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003034
Ted Kremenek6cd69422010-07-19 22:01:06 +00003035 if (FS.consumesDataArgument()) {
3036 if (atFirstArg) {
3037 atFirstArg = false;
3038 usesPositionalArgs = FS.usesPositionalArg();
3039 }
3040 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003041 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3042 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003043 return false;
3044 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003045 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003046
Ted Kremenekd1668192010-02-27 01:41:03 +00003047 // First check if the field width, precision, and conversion specifier
3048 // have matching data arguments.
3049 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3050 startSpecifier, specifierLen)) {
3051 return false;
3052 }
3053
3054 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3055 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003056 return false;
3057 }
3058
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003059 if (!CS.consumesDataArgument()) {
3060 // FIXME: Technically specifying a precision or field width here
3061 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003062 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003063 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003064
Ted Kremenek4a49d982010-02-26 19:18:41 +00003065 // Consume the argument.
3066 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003067 if (argIndex < NumDataArgs) {
3068 // The check to see if the argIndex is valid will come later.
3069 // We set the bit here because we may exit early from this
3070 // function if we encounter some other error.
3071 CoveredArgs.set(argIndex);
3072 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003073
3074 // Check for using an Objective-C specific conversion specifier
3075 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003076 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003077 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3078 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003079 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003080
Tom Careb49ec692010-06-17 19:00:27 +00003081 // Check for invalid use of field width
3082 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003083 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003084 startSpecifier, specifierLen);
3085 }
3086
3087 // Check for invalid use of precision
3088 if (!FS.hasValidPrecision()) {
3089 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3090 startSpecifier, specifierLen);
3091 }
3092
3093 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003094 if (!FS.hasValidThousandsGroupingPrefix())
3095 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003096 if (!FS.hasValidLeadingZeros())
3097 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3098 if (!FS.hasValidPlusPrefix())
3099 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003100 if (!FS.hasValidSpacePrefix())
3101 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003102 if (!FS.hasValidAlternativeForm())
3103 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3104 if (!FS.hasValidLeftJustified())
3105 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3106
3107 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003108 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3109 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3110 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003111 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3112 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3113 startSpecifier, specifierLen);
3114
3115 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003116 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003117 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3118 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003119 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003120 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003121 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003122 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3123 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003124
Jordan Rose92303592012-09-08 04:00:03 +00003125 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3126 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3127
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003128 // The remaining checks depend on the data arguments.
3129 if (HasVAListArg)
3130 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003131
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003132 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003133 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003134
Jordan Rose58bbe422012-07-19 18:10:08 +00003135 const Expr *Arg = getDataArg(argIndex);
3136 if (!Arg)
3137 return true;
3138
3139 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003140}
3141
Jordan Roseaee34382012-09-05 22:56:26 +00003142static bool requiresParensToAddCast(const Expr *E) {
3143 // FIXME: We should have a general way to reason about operator
3144 // precedence and whether parens are actually needed here.
3145 // Take care of a few common cases where they aren't.
3146 const Expr *Inside = E->IgnoreImpCasts();
3147 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3148 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3149
3150 switch (Inside->getStmtClass()) {
3151 case Stmt::ArraySubscriptExprClass:
3152 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003153 case Stmt::CharacterLiteralClass:
3154 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003155 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003156 case Stmt::FloatingLiteralClass:
3157 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003158 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003159 case Stmt::ObjCArrayLiteralClass:
3160 case Stmt::ObjCBoolLiteralExprClass:
3161 case Stmt::ObjCBoxedExprClass:
3162 case Stmt::ObjCDictionaryLiteralClass:
3163 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003164 case Stmt::ObjCIvarRefExprClass:
3165 case Stmt::ObjCMessageExprClass:
3166 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003167 case Stmt::ObjCStringLiteralClass:
3168 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003169 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003170 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003171 case Stmt::UnaryOperatorClass:
3172 return false;
3173 default:
3174 return true;
3175 }
3176}
3177
Richard Smith55ce3522012-06-25 20:30:08 +00003178bool
3179CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3180 const char *StartSpecifier,
3181 unsigned SpecifierLen,
3182 const Expr *E) {
3183 using namespace analyze_format_string;
3184 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003185 // Now type check the data expression that matches the
3186 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003187 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3188 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003189 if (!AT.isValid())
3190 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003191
Jordan Rose598ec092012-12-05 18:44:40 +00003192 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003193 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3194 ExprTy = TET->getUnderlyingExpr()->getType();
3195 }
3196
Jordan Rose598ec092012-12-05 18:44:40 +00003197 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003198 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003199
Jordan Rose22b74712012-09-05 22:56:19 +00003200 // Look through argument promotions for our error message's reported type.
3201 // This includes the integral and floating promotions, but excludes array
3202 // and function pointer decay; seeing that an argument intended to be a
3203 // string has type 'char [6]' is probably more confusing than 'char *'.
3204 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3205 if (ICE->getCastKind() == CK_IntegralCast ||
3206 ICE->getCastKind() == CK_FloatingCast) {
3207 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003208 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003209
3210 // Check if we didn't match because of an implicit cast from a 'char'
3211 // or 'short' to an 'int'. This is done because printf is a varargs
3212 // function.
3213 if (ICE->getType() == S.Context.IntTy ||
3214 ICE->getType() == S.Context.UnsignedIntTy) {
3215 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003216 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003217 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003218 }
Jordan Rose98709982012-06-04 22:48:57 +00003219 }
Jordan Rose598ec092012-12-05 18:44:40 +00003220 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3221 // Special case for 'a', which has type 'int' in C.
3222 // Note, however, that we do /not/ want to treat multibyte constants like
3223 // 'MooV' as characters! This form is deprecated but still exists.
3224 if (ExprTy == S.Context.IntTy)
3225 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3226 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003227 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003228
Jordan Rosebc53ed12014-05-31 04:12:14 +00003229 // Look through enums to their underlying type.
3230 bool IsEnum = false;
3231 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3232 ExprTy = EnumTy->getDecl()->getIntegerType();
3233 IsEnum = true;
3234 }
3235
Jordan Rose0e5badd2012-12-05 18:44:49 +00003236 // %C in an Objective-C context prints a unichar, not a wchar_t.
3237 // If the argument is an integer of some kind, believe the %C and suggest
3238 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003239 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003240 if (ObjCContext &&
3241 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3242 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3243 !ExprTy->isCharType()) {
3244 // 'unichar' is defined as a typedef of unsigned short, but we should
3245 // prefer using the typedef if it is visible.
3246 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003247
3248 // While we are here, check if the value is an IntegerLiteral that happens
3249 // to be within the valid range.
3250 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3251 const llvm::APInt &V = IL->getValue();
3252 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3253 return true;
3254 }
3255
Jordan Rose0e5badd2012-12-05 18:44:49 +00003256 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3257 Sema::LookupOrdinaryName);
3258 if (S.LookupName(Result, S.getCurScope())) {
3259 NamedDecl *ND = Result.getFoundDecl();
3260 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3261 if (TD->getUnderlyingType() == IntendedTy)
3262 IntendedTy = S.Context.getTypedefType(TD);
3263 }
3264 }
3265 }
3266
3267 // Special-case some of Darwin's platform-independence types by suggesting
3268 // casts to primitive types that are known to be large enough.
3269 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003270 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003271 // Use a 'while' to peel off layers of typedefs.
3272 QualType TyTy = IntendedTy;
3273 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003274 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003275 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003276 .Case("NSInteger", S.Context.LongTy)
3277 .Case("NSUInteger", S.Context.UnsignedLongTy)
3278 .Case("SInt32", S.Context.IntTy)
3279 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003280 .Default(QualType());
3281
3282 if (!CastTy.isNull()) {
3283 ShouldNotPrintDirectly = true;
3284 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003285 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003286 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003287 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003288 }
3289 }
3290
Jordan Rose22b74712012-09-05 22:56:19 +00003291 // We may be able to offer a FixItHint if it is a supported type.
3292 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003293 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003294 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003295
Jordan Rose22b74712012-09-05 22:56:19 +00003296 if (success) {
3297 // Get the fix string from the fixed format specifier
3298 SmallString<16> buf;
3299 llvm::raw_svector_ostream os(buf);
3300 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003301
Jordan Roseaee34382012-09-05 22:56:26 +00003302 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3303
Jordan Rose0e5badd2012-12-05 18:44:49 +00003304 if (IntendedTy == ExprTy) {
3305 // In this case, the specifier is wrong and should be changed to match
3306 // the argument.
3307 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003308 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3309 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003310 << E->getSourceRange(),
3311 E->getLocStart(),
3312 /*IsStringLocation*/false,
3313 SpecRange,
3314 FixItHint::CreateReplacement(SpecRange, os.str()));
3315
3316 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003317 // The canonical type for formatting this value is different from the
3318 // actual type of the expression. (This occurs, for example, with Darwin's
3319 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3320 // should be printed as 'long' for 64-bit compatibility.)
3321 // Rather than emitting a normal format/argument mismatch, we want to
3322 // add a cast to the recommended type (and correct the format string
3323 // if necessary).
3324 SmallString<16> CastBuf;
3325 llvm::raw_svector_ostream CastFix(CastBuf);
3326 CastFix << "(";
3327 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3328 CastFix << ")";
3329
3330 SmallVector<FixItHint,4> Hints;
3331 if (!AT.matchesType(S.Context, IntendedTy))
3332 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3333
3334 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3335 // If there's already a cast present, just replace it.
3336 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3337 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3338
3339 } else if (!requiresParensToAddCast(E)) {
3340 // If the expression has high enough precedence,
3341 // just write the C-style cast.
3342 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3343 CastFix.str()));
3344 } else {
3345 // Otherwise, add parens around the expression as well as the cast.
3346 CastFix << "(";
3347 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3348 CastFix.str()));
3349
Alp Tokerb6cc5922014-05-03 03:45:55 +00003350 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003351 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3352 }
3353
Jordan Rose0e5badd2012-12-05 18:44:49 +00003354 if (ShouldNotPrintDirectly) {
3355 // The expression has a type that should not be printed directly.
3356 // We extract the name from the typedef because we don't want to show
3357 // the underlying type in the diagnostic.
3358 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003359
Jordan Rose0e5badd2012-12-05 18:44:49 +00003360 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003361 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003362 << E->getSourceRange(),
3363 E->getLocStart(), /*IsStringLocation=*/false,
3364 SpecRange, Hints);
3365 } else {
3366 // In this case, the expression could be printed using a different
3367 // specifier, but we've decided that the specifier is probably correct
3368 // and we should cast instead. Just use the normal warning message.
3369 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003370 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3371 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003372 << E->getSourceRange(),
3373 E->getLocStart(), /*IsStringLocation*/false,
3374 SpecRange, Hints);
3375 }
Jordan Roseaee34382012-09-05 22:56:26 +00003376 }
Jordan Rose22b74712012-09-05 22:56:19 +00003377 } else {
3378 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3379 SpecifierLen);
3380 // Since the warning for passing non-POD types to variadic functions
3381 // was deferred until now, we emit a warning for non-POD
3382 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003383 switch (S.isValidVarArgType(ExprTy)) {
3384 case Sema::VAK_Valid:
3385 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003386 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003387 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3388 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003389 << CSR
3390 << E->getSourceRange(),
3391 E->getLocStart(), /*IsStringLocation*/false, CSR);
3392 break;
3393
3394 case Sema::VAK_Undefined:
3395 EmitFormatDiagnostic(
3396 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003397 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003398 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003399 << CallType
3400 << AT.getRepresentativeTypeName(S.Context)
3401 << CSR
3402 << E->getSourceRange(),
3403 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003404 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003405 break;
3406
3407 case Sema::VAK_Invalid:
3408 if (ExprTy->isObjCObjectType())
3409 EmitFormatDiagnostic(
3410 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3411 << S.getLangOpts().CPlusPlus11
3412 << ExprTy
3413 << CallType
3414 << AT.getRepresentativeTypeName(S.Context)
3415 << CSR
3416 << E->getSourceRange(),
3417 E->getLocStart(), /*IsStringLocation*/false, CSR);
3418 else
3419 // FIXME: If this is an initializer list, suggest removing the braces
3420 // or inserting a cast to the target type.
3421 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3422 << isa<InitListExpr>(E) << ExprTy << CallType
3423 << AT.getRepresentativeTypeName(S.Context)
3424 << E->getSourceRange();
3425 break;
3426 }
3427
3428 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3429 "format string specifier index out of range");
3430 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003431 }
3432
Ted Kremenekab278de2010-01-28 23:39:18 +00003433 return true;
3434}
3435
Ted Kremenek02087932010-07-16 02:11:22 +00003436//===--- CHECK: Scanf format string checking ------------------------------===//
3437
3438namespace {
3439class CheckScanfHandler : public CheckFormatHandler {
3440public:
3441 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3442 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003443 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003444 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003445 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003446 Sema::VariadicCallType CallType,
3447 llvm::SmallBitVector &CheckedVarArgs)
3448 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3449 numDataArgs, beg, hasVAListArg,
3450 Args, formatIdx, inFunctionCall, CallType,
3451 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003452 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003453
3454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3455 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003456 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003457
3458 bool HandleInvalidScanfConversionSpecifier(
3459 const analyze_scanf::ScanfSpecifier &FS,
3460 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003461 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003462
Craig Toppere14c0f82014-03-12 04:55:44 +00003463 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003464};
Ted Kremenek019d2242010-01-29 01:50:07 +00003465}
Ted Kremenekab278de2010-01-28 23:39:18 +00003466
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003467void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3468 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003469 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3470 getLocationOfByte(end), /*IsStringLocation*/true,
3471 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003472}
3473
Ted Kremenekce815422010-07-19 21:25:57 +00003474bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3475 const analyze_scanf::ScanfSpecifier &FS,
3476 const char *startSpecifier,
3477 unsigned specifierLen) {
3478
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003479 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003480 FS.getConversionSpecifier();
3481
3482 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3483 getLocationOfByte(CS.getStart()),
3484 startSpecifier, specifierLen,
3485 CS.getStart(), CS.getLength());
3486}
3487
Ted Kremenek02087932010-07-16 02:11:22 +00003488bool CheckScanfHandler::HandleScanfSpecifier(
3489 const analyze_scanf::ScanfSpecifier &FS,
3490 const char *startSpecifier,
3491 unsigned specifierLen) {
3492
3493 using namespace analyze_scanf;
3494 using namespace analyze_format_string;
3495
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003496 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003497
Ted Kremenek6cd69422010-07-19 22:01:06 +00003498 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3499 // be used to decide if we are using positional arguments consistently.
3500 if (FS.consumesDataArgument()) {
3501 if (atFirstArg) {
3502 atFirstArg = false;
3503 usesPositionalArgs = FS.usesPositionalArg();
3504 }
3505 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003506 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3507 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003508 return false;
3509 }
Ted Kremenek02087932010-07-16 02:11:22 +00003510 }
3511
3512 // Check if the field with is non-zero.
3513 const OptionalAmount &Amt = FS.getFieldWidth();
3514 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3515 if (Amt.getConstantAmount() == 0) {
3516 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3517 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003518 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3519 getLocationOfByte(Amt.getStart()),
3520 /*IsStringLocation*/true, R,
3521 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003522 }
3523 }
3524
3525 if (!FS.consumesDataArgument()) {
3526 // FIXME: Technically specifying a precision or field width here
3527 // makes no sense. Worth issuing a warning at some point.
3528 return true;
3529 }
3530
3531 // Consume the argument.
3532 unsigned argIndex = FS.getArgIndex();
3533 if (argIndex < NumDataArgs) {
3534 // The check to see if the argIndex is valid will come later.
3535 // We set the bit here because we may exit early from this
3536 // function if we encounter some other error.
3537 CoveredArgs.set(argIndex);
3538 }
3539
Ted Kremenek4407ea42010-07-20 20:04:47 +00003540 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003541 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003542 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3543 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003544 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003545 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003546 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003547 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3548 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003549
Jordan Rose92303592012-09-08 04:00:03 +00003550 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3551 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3552
Ted Kremenek02087932010-07-16 02:11:22 +00003553 // The remaining checks depend on the data arguments.
3554 if (HasVAListArg)
3555 return true;
3556
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003557 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003558 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003559
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003560 // Check that the argument type matches the format specifier.
3561 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003562 if (!Ex)
3563 return true;
3564
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003565 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3566 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003567 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003568 bool success = fixedFS.fixType(Ex->getType(),
3569 Ex->IgnoreImpCasts()->getType(),
3570 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003571
3572 if (success) {
3573 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003574 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003575 llvm::raw_svector_ostream os(buf);
3576 fixedFS.toString(os);
3577
3578 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003579 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3580 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003581 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003582 Ex->getLocStart(),
3583 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003584 getSpecifierRange(startSpecifier, specifierLen),
3585 FixItHint::CreateReplacement(
3586 getSpecifierRange(startSpecifier, specifierLen),
3587 os.str()));
3588 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003589 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003590 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3591 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003592 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003593 Ex->getLocStart(),
3594 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003595 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003596 }
3597 }
3598
Ted Kremenek02087932010-07-16 02:11:22 +00003599 return true;
3600}
3601
3602void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003603 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003604 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003605 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003606 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003607 bool inFunctionCall, VariadicCallType CallType,
3608 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003609
Ted Kremenekab278de2010-01-28 23:39:18 +00003610 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003611 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003612 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003613 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003614 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3615 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003616 return;
3617 }
Ted Kremenek02087932010-07-16 02:11:22 +00003618
Ted Kremenekab278de2010-01-28 23:39:18 +00003619 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003620 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003621 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003622 // Account for cases where the string literal is truncated in a declaration.
3623 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3624 assert(T && "String literal not of constant array type!");
3625 size_t TypeSize = T->getSize().getZExtValue();
3626 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003627 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003628
3629 // Emit a warning if the string literal is truncated and does not contain an
3630 // embedded null character.
3631 if (TypeSize <= StrRef.size() &&
3632 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3633 CheckFormatHandler::EmitFormatDiagnostic(
3634 *this, inFunctionCall, Args[format_idx],
3635 PDiag(diag::warn_printf_format_string_not_null_terminated),
3636 FExpr->getLocStart(),
3637 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3638 return;
3639 }
3640
Ted Kremenekab278de2010-01-28 23:39:18 +00003641 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003642 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003643 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003644 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003645 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3646 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003647 return;
3648 }
Ted Kremenek02087932010-07-16 02:11:22 +00003649
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003650 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003651 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003652 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003653 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003654 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003655
Hans Wennborg23926bd2011-12-15 10:25:47 +00003656 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003657 getLangOpts(),
3658 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003659 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003660 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003661 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003662 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003663 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003664
Hans Wennborg23926bd2011-12-15 10:25:47 +00003665 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003666 getLangOpts(),
3667 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003668 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003669 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003670}
3671
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003672//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3673
3674// Returns the related absolute value function that is larger, of 0 if one
3675// does not exist.
3676static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3677 switch (AbsFunction) {
3678 default:
3679 return 0;
3680
3681 case Builtin::BI__builtin_abs:
3682 return Builtin::BI__builtin_labs;
3683 case Builtin::BI__builtin_labs:
3684 return Builtin::BI__builtin_llabs;
3685 case Builtin::BI__builtin_llabs:
3686 return 0;
3687
3688 case Builtin::BI__builtin_fabsf:
3689 return Builtin::BI__builtin_fabs;
3690 case Builtin::BI__builtin_fabs:
3691 return Builtin::BI__builtin_fabsl;
3692 case Builtin::BI__builtin_fabsl:
3693 return 0;
3694
3695 case Builtin::BI__builtin_cabsf:
3696 return Builtin::BI__builtin_cabs;
3697 case Builtin::BI__builtin_cabs:
3698 return Builtin::BI__builtin_cabsl;
3699 case Builtin::BI__builtin_cabsl:
3700 return 0;
3701
3702 case Builtin::BIabs:
3703 return Builtin::BIlabs;
3704 case Builtin::BIlabs:
3705 return Builtin::BIllabs;
3706 case Builtin::BIllabs:
3707 return 0;
3708
3709 case Builtin::BIfabsf:
3710 return Builtin::BIfabs;
3711 case Builtin::BIfabs:
3712 return Builtin::BIfabsl;
3713 case Builtin::BIfabsl:
3714 return 0;
3715
3716 case Builtin::BIcabsf:
3717 return Builtin::BIcabs;
3718 case Builtin::BIcabs:
3719 return Builtin::BIcabsl;
3720 case Builtin::BIcabsl:
3721 return 0;
3722 }
3723}
3724
3725// Returns the argument type of the absolute value function.
3726static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3727 unsigned AbsType) {
3728 if (AbsType == 0)
3729 return QualType();
3730
3731 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3732 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3733 if (Error != ASTContext::GE_None)
3734 return QualType();
3735
3736 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3737 if (!FT)
3738 return QualType();
3739
3740 if (FT->getNumParams() != 1)
3741 return QualType();
3742
3743 return FT->getParamType(0);
3744}
3745
3746// Returns the best absolute value function, or zero, based on type and
3747// current absolute value function.
3748static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3749 unsigned AbsFunctionKind) {
3750 unsigned BestKind = 0;
3751 uint64_t ArgSize = Context.getTypeSize(ArgType);
3752 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3753 Kind = getLargerAbsoluteValueFunction(Kind)) {
3754 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3755 if (Context.getTypeSize(ParamType) >= ArgSize) {
3756 if (BestKind == 0)
3757 BestKind = Kind;
3758 else if (Context.hasSameType(ParamType, ArgType)) {
3759 BestKind = Kind;
3760 break;
3761 }
3762 }
3763 }
3764 return BestKind;
3765}
3766
3767enum AbsoluteValueKind {
3768 AVK_Integer,
3769 AVK_Floating,
3770 AVK_Complex
3771};
3772
3773static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3774 if (T->isIntegralOrEnumerationType())
3775 return AVK_Integer;
3776 if (T->isRealFloatingType())
3777 return AVK_Floating;
3778 if (T->isAnyComplexType())
3779 return AVK_Complex;
3780
3781 llvm_unreachable("Type not integer, floating, or complex");
3782}
3783
3784// Changes the absolute value function to a different type. Preserves whether
3785// the function is a builtin.
3786static unsigned changeAbsFunction(unsigned AbsKind,
3787 AbsoluteValueKind ValueKind) {
3788 switch (ValueKind) {
3789 case AVK_Integer:
3790 switch (AbsKind) {
3791 default:
3792 return 0;
3793 case Builtin::BI__builtin_fabsf:
3794 case Builtin::BI__builtin_fabs:
3795 case Builtin::BI__builtin_fabsl:
3796 case Builtin::BI__builtin_cabsf:
3797 case Builtin::BI__builtin_cabs:
3798 case Builtin::BI__builtin_cabsl:
3799 return Builtin::BI__builtin_abs;
3800 case Builtin::BIfabsf:
3801 case Builtin::BIfabs:
3802 case Builtin::BIfabsl:
3803 case Builtin::BIcabsf:
3804 case Builtin::BIcabs:
3805 case Builtin::BIcabsl:
3806 return Builtin::BIabs;
3807 }
3808 case AVK_Floating:
3809 switch (AbsKind) {
3810 default:
3811 return 0;
3812 case Builtin::BI__builtin_abs:
3813 case Builtin::BI__builtin_labs:
3814 case Builtin::BI__builtin_llabs:
3815 case Builtin::BI__builtin_cabsf:
3816 case Builtin::BI__builtin_cabs:
3817 case Builtin::BI__builtin_cabsl:
3818 return Builtin::BI__builtin_fabsf;
3819 case Builtin::BIabs:
3820 case Builtin::BIlabs:
3821 case Builtin::BIllabs:
3822 case Builtin::BIcabsf:
3823 case Builtin::BIcabs:
3824 case Builtin::BIcabsl:
3825 return Builtin::BIfabsf;
3826 }
3827 case AVK_Complex:
3828 switch (AbsKind) {
3829 default:
3830 return 0;
3831 case Builtin::BI__builtin_abs:
3832 case Builtin::BI__builtin_labs:
3833 case Builtin::BI__builtin_llabs:
3834 case Builtin::BI__builtin_fabsf:
3835 case Builtin::BI__builtin_fabs:
3836 case Builtin::BI__builtin_fabsl:
3837 return Builtin::BI__builtin_cabsf;
3838 case Builtin::BIabs:
3839 case Builtin::BIlabs:
3840 case Builtin::BIllabs:
3841 case Builtin::BIfabsf:
3842 case Builtin::BIfabs:
3843 case Builtin::BIfabsl:
3844 return Builtin::BIcabsf;
3845 }
3846 }
3847 llvm_unreachable("Unable to convert function");
3848}
3849
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003850static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003851 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3852 if (!FnInfo)
3853 return 0;
3854
3855 switch (FDecl->getBuiltinID()) {
3856 default:
3857 return 0;
3858 case Builtin::BI__builtin_abs:
3859 case Builtin::BI__builtin_fabs:
3860 case Builtin::BI__builtin_fabsf:
3861 case Builtin::BI__builtin_fabsl:
3862 case Builtin::BI__builtin_labs:
3863 case Builtin::BI__builtin_llabs:
3864 case Builtin::BI__builtin_cabs:
3865 case Builtin::BI__builtin_cabsf:
3866 case Builtin::BI__builtin_cabsl:
3867 case Builtin::BIabs:
3868 case Builtin::BIlabs:
3869 case Builtin::BIllabs:
3870 case Builtin::BIfabs:
3871 case Builtin::BIfabsf:
3872 case Builtin::BIfabsl:
3873 case Builtin::BIcabs:
3874 case Builtin::BIcabsf:
3875 case Builtin::BIcabsl:
3876 return FDecl->getBuiltinID();
3877 }
3878 llvm_unreachable("Unknown Builtin type");
3879}
3880
3881// If the replacement is valid, emit a note with replacement function.
3882// Additionally, suggest including the proper header if not already included.
3883static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003884 unsigned AbsKind, QualType ArgType) {
3885 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003886 const char *HeaderName = nullptr;
3887 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003888 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3889 FunctionName = "std::abs";
3890 if (ArgType->isIntegralOrEnumerationType()) {
3891 HeaderName = "cstdlib";
3892 } else if (ArgType->isRealFloatingType()) {
3893 HeaderName = "cmath";
3894 } else {
3895 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003896 }
Richard Trieubeffb832014-04-15 23:47:53 +00003897
3898 // Lookup all std::abs
3899 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003900 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003901 R.suppressDiagnostics();
3902 S.LookupQualifiedName(R, Std);
3903
3904 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003905 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003906 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3907 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3908 } else {
3909 FDecl = dyn_cast<FunctionDecl>(I);
3910 }
3911 if (!FDecl)
3912 continue;
3913
3914 // Found std::abs(), check that they are the right ones.
3915 if (FDecl->getNumParams() != 1)
3916 continue;
3917
3918 // Check that the parameter type can handle the argument.
3919 QualType ParamType = FDecl->getParamDecl(0)->getType();
3920 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3921 S.Context.getTypeSize(ArgType) <=
3922 S.Context.getTypeSize(ParamType)) {
3923 // Found a function, don't need the header hint.
3924 EmitHeaderHint = false;
3925 break;
3926 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003927 }
Richard Trieubeffb832014-04-15 23:47:53 +00003928 }
3929 } else {
3930 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3931 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3932
3933 if (HeaderName) {
3934 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3935 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3936 R.suppressDiagnostics();
3937 S.LookupName(R, S.getCurScope());
3938
3939 if (R.isSingleResult()) {
3940 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3941 if (FD && FD->getBuiltinID() == AbsKind) {
3942 EmitHeaderHint = false;
3943 } else {
3944 return;
3945 }
3946 } else if (!R.empty()) {
3947 return;
3948 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003949 }
3950 }
3951
3952 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003953 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003954
Richard Trieubeffb832014-04-15 23:47:53 +00003955 if (!HeaderName)
3956 return;
3957
3958 if (!EmitHeaderHint)
3959 return;
3960
Alp Toker5d96e0a2014-07-11 20:53:51 +00003961 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3962 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003963}
3964
3965static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3966 if (!FDecl)
3967 return false;
3968
3969 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3970 return false;
3971
3972 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3973
3974 while (ND && ND->isInlineNamespace()) {
3975 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003976 }
Richard Trieubeffb832014-04-15 23:47:53 +00003977
3978 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3979 return false;
3980
3981 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3982 return false;
3983
3984 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003985}
3986
3987// Warn when using the wrong abs() function.
3988void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3989 const FunctionDecl *FDecl,
3990 IdentifierInfo *FnInfo) {
3991 if (Call->getNumArgs() != 1)
3992 return;
3993
3994 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003995 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3996 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003997 return;
3998
3999 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4000 QualType ParamType = Call->getArg(0)->getType();
4001
Alp Toker5d96e0a2014-07-11 20:53:51 +00004002 // Unsigned types cannot be negative. Suggest removing the absolute value
4003 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004004 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004005 const char *FunctionName =
4006 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004007 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4008 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004009 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004010 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4011 return;
4012 }
4013
Richard Trieubeffb832014-04-15 23:47:53 +00004014 // std::abs has overloads which prevent most of the absolute value problems
4015 // from occurring.
4016 if (IsStdAbs)
4017 return;
4018
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004019 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4020 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4021
4022 // The argument and parameter are the same kind. Check if they are the right
4023 // size.
4024 if (ArgValueKind == ParamValueKind) {
4025 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4026 return;
4027
4028 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4029 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4030 << FDecl << ArgType << ParamType;
4031
4032 if (NewAbsKind == 0)
4033 return;
4034
4035 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004036 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004037 return;
4038 }
4039
4040 // ArgValueKind != ParamValueKind
4041 // The wrong type of absolute value function was used. Attempt to find the
4042 // proper one.
4043 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4044 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4045 if (NewAbsKind == 0)
4046 return;
4047
4048 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4049 << FDecl << ParamValueKind << ArgValueKind;
4050
4051 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004052 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004053 return;
4054}
4055
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004056//===--- CHECK: Standard memory functions ---------------------------------===//
4057
Nico Weber0e6daef2013-12-26 23:38:39 +00004058/// \brief Takes the expression passed to the size_t parameter of functions
4059/// such as memcmp, strncat, etc and warns if it's a comparison.
4060///
4061/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4062static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4063 IdentifierInfo *FnName,
4064 SourceLocation FnLoc,
4065 SourceLocation RParenLoc) {
4066 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4067 if (!Size)
4068 return false;
4069
4070 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4071 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4072 return false;
4073
Nico Weber0e6daef2013-12-26 23:38:39 +00004074 SourceRange SizeRange = Size->getSourceRange();
4075 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4076 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004077 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004078 << FnName << FixItHint::CreateInsertion(
4079 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004080 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004081 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004082 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004083 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4084 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004085
4086 return true;
4087}
4088
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004089/// \brief Determine whether the given type is or contains a dynamic class type
4090/// (e.g., whether it has a vtable).
4091static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4092 bool &IsContained) {
4093 // Look through array types while ignoring qualifiers.
4094 const Type *Ty = T->getBaseElementTypeUnsafe();
4095 IsContained = false;
4096
4097 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4098 RD = RD ? RD->getDefinition() : nullptr;
4099 if (!RD)
4100 return nullptr;
4101
4102 if (RD->isDynamicClass())
4103 return RD;
4104
4105 // Check all the fields. If any bases were dynamic, the class is dynamic.
4106 // It's impossible for a class to transitively contain itself by value, so
4107 // infinite recursion is impossible.
4108 for (auto *FD : RD->fields()) {
4109 bool SubContained;
4110 if (const CXXRecordDecl *ContainedRD =
4111 getContainedDynamicClass(FD->getType(), SubContained)) {
4112 IsContained = true;
4113 return ContainedRD;
4114 }
4115 }
4116
4117 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004118}
4119
Chandler Carruth889ed862011-06-21 23:04:20 +00004120/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004121/// otherwise returns NULL.
4122static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004123 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004124 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4125 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4126 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004127
Craig Topperc3ec1492014-05-26 06:22:03 +00004128 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004129}
4130
Chandler Carruth889ed862011-06-21 23:04:20 +00004131/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004132static QualType getSizeOfArgType(const Expr* E) {
4133 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4134 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4135 if (SizeOf->getKind() == clang::UETT_SizeOf)
4136 return SizeOf->getTypeOfArgument();
4137
4138 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004139}
4140
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004141/// \brief Check for dangerous or invalid arguments to memset().
4142///
Chandler Carruthac687262011-06-03 06:23:57 +00004143/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004144/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4145/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004146///
4147/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004148void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004149 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004150 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004151 assert(BId != 0);
4152
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004153 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004154 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004155 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004156 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004157 return;
4158
Anna Zaks22122702012-01-17 00:37:07 +00004159 unsigned LastArg = (BId == Builtin::BImemset ||
4160 BId == Builtin::BIstrndup ? 1 : 2);
4161 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004162 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004163
Nico Weber0e6daef2013-12-26 23:38:39 +00004164 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4165 Call->getLocStart(), Call->getRParenLoc()))
4166 return;
4167
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004168 // We have special checking when the length is a sizeof expression.
4169 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4170 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4171 llvm::FoldingSetNodeID SizeOfArgID;
4172
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004173 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4174 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004175 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004176
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004177 QualType DestTy = Dest->getType();
4178 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4179 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004180
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004181 // Never warn about void type pointers. This can be used to suppress
4182 // false positives.
4183 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004184 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004185
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004186 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4187 // actually comparing the expressions for equality. Because computing the
4188 // expression IDs can be expensive, we only do this if the diagnostic is
4189 // enabled.
4190 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004191 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4192 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004193 // We only compute IDs for expressions if the warning is enabled, and
4194 // cache the sizeof arg's ID.
4195 if (SizeOfArgID == llvm::FoldingSetNodeID())
4196 SizeOfArg->Profile(SizeOfArgID, Context, true);
4197 llvm::FoldingSetNodeID DestID;
4198 Dest->Profile(DestID, Context, true);
4199 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004200 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4201 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004202 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004203 StringRef ReadableName = FnName->getName();
4204
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004205 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004206 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004207 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004208 if (!PointeeTy->isIncompleteType() &&
4209 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004210 ActionIdx = 2; // If the pointee's size is sizeof(char),
4211 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004212
4213 // If the function is defined as a builtin macro, do not show macro
4214 // expansion.
4215 SourceLocation SL = SizeOfArg->getExprLoc();
4216 SourceRange DSR = Dest->getSourceRange();
4217 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004218 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004219
4220 if (SM.isMacroArgExpansion(SL)) {
4221 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4222 SL = SM.getSpellingLoc(SL);
4223 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4224 SM.getSpellingLoc(DSR.getEnd()));
4225 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4226 SM.getSpellingLoc(SSR.getEnd()));
4227 }
4228
Anna Zaksd08d9152012-05-30 23:14:52 +00004229 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004230 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004231 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004232 << PointeeTy
4233 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004234 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004235 << SSR);
4236 DiagRuntimeBehavior(SL, SizeOfArg,
4237 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4238 << ActionIdx
4239 << SSR);
4240
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004241 break;
4242 }
4243 }
4244
4245 // Also check for cases where the sizeof argument is the exact same
4246 // type as the memory argument, and where it points to a user-defined
4247 // record type.
4248 if (SizeOfArgTy != QualType()) {
4249 if (PointeeTy->isRecordType() &&
4250 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4251 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4252 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4253 << FnName << SizeOfArgTy << ArgIdx
4254 << PointeeTy << Dest->getSourceRange()
4255 << LenExpr->getSourceRange());
4256 break;
4257 }
Nico Weberc5e73862011-06-14 16:14:58 +00004258 }
4259
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004260 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004261 bool IsContained;
4262 if (const CXXRecordDecl *ContainedRD =
4263 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004264
4265 unsigned OperationType = 0;
4266 // "overwritten" if we're warning about the destination for any call
4267 // but memcmp; otherwise a verb appropriate to the call.
4268 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4269 if (BId == Builtin::BImemcpy)
4270 OperationType = 1;
4271 else if(BId == Builtin::BImemmove)
4272 OperationType = 2;
4273 else if (BId == Builtin::BImemcmp)
4274 OperationType = 3;
4275 }
4276
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004277 DiagRuntimeBehavior(
4278 Dest->getExprLoc(), Dest,
4279 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004280 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004281 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004282 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004283 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4284 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004285 DiagRuntimeBehavior(
4286 Dest->getExprLoc(), Dest,
4287 PDiag(diag::warn_arc_object_memaccess)
4288 << ArgIdx << FnName << PointeeTy
4289 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004290 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004291 continue;
John McCall31168b02011-06-15 23:02:42 +00004292
4293 DiagRuntimeBehavior(
4294 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004295 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004296 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4297 break;
4298 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004299 }
4300}
4301
Ted Kremenek6865f772011-08-18 20:55:45 +00004302// A little helper routine: ignore addition and subtraction of integer literals.
4303// This intentionally does not ignore all integer constant expressions because
4304// we don't want to remove sizeof().
4305static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4306 Ex = Ex->IgnoreParenCasts();
4307
4308 for (;;) {
4309 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4310 if (!BO || !BO->isAdditiveOp())
4311 break;
4312
4313 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4314 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4315
4316 if (isa<IntegerLiteral>(RHS))
4317 Ex = LHS;
4318 else if (isa<IntegerLiteral>(LHS))
4319 Ex = RHS;
4320 else
4321 break;
4322 }
4323
4324 return Ex;
4325}
4326
Anna Zaks13b08572012-08-08 21:42:23 +00004327static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4328 ASTContext &Context) {
4329 // Only handle constant-sized or VLAs, but not flexible members.
4330 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4331 // Only issue the FIXIT for arrays of size > 1.
4332 if (CAT->getSize().getSExtValue() <= 1)
4333 return false;
4334 } else if (!Ty->isVariableArrayType()) {
4335 return false;
4336 }
4337 return true;
4338}
4339
Ted Kremenek6865f772011-08-18 20:55:45 +00004340// Warn if the user has made the 'size' argument to strlcpy or strlcat
4341// be the size of the source, instead of the destination.
4342void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4343 IdentifierInfo *FnName) {
4344
4345 // Don't crash if the user has the wrong number of arguments
4346 if (Call->getNumArgs() != 3)
4347 return;
4348
4349 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4350 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004351 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004352
4353 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4354 Call->getLocStart(), Call->getRParenLoc()))
4355 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004356
4357 // Look for 'strlcpy(dst, x, sizeof(x))'
4358 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4359 CompareWithSrc = Ex;
4360 else {
4361 // Look for 'strlcpy(dst, x, strlen(x))'
4362 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004363 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4364 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004365 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4366 }
4367 }
4368
4369 if (!CompareWithSrc)
4370 return;
4371
4372 // Determine if the argument to sizeof/strlen is equal to the source
4373 // argument. In principle there's all kinds of things you could do
4374 // here, for instance creating an == expression and evaluating it with
4375 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4376 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4377 if (!SrcArgDRE)
4378 return;
4379
4380 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4381 if (!CompareWithSrcDRE ||
4382 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4383 return;
4384
4385 const Expr *OriginalSizeArg = Call->getArg(2);
4386 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4387 << OriginalSizeArg->getSourceRange() << FnName;
4388
4389 // Output a FIXIT hint if the destination is an array (rather than a
4390 // pointer to an array). This could be enhanced to handle some
4391 // pointers if we know the actual size, like if DstArg is 'array+2'
4392 // we could say 'sizeof(array)-2'.
4393 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004394 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004395 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004396
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004397 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004398 llvm::raw_svector_ostream OS(sizeString);
4399 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004400 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004401 OS << ")";
4402
4403 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4404 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4405 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004406}
4407
Anna Zaks314cd092012-02-01 19:08:57 +00004408/// Check if two expressions refer to the same declaration.
4409static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4410 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4411 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4412 return D1->getDecl() == D2->getDecl();
4413 return false;
4414}
4415
4416static const Expr *getStrlenExprArg(const Expr *E) {
4417 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4418 const FunctionDecl *FD = CE->getDirectCallee();
4419 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004420 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004421 return CE->getArg(0)->IgnoreParenCasts();
4422 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004423 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004424}
4425
4426// Warn on anti-patterns as the 'size' argument to strncat.
4427// The correct size argument should look like following:
4428// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4429void Sema::CheckStrncatArguments(const CallExpr *CE,
4430 IdentifierInfo *FnName) {
4431 // Don't crash if the user has the wrong number of arguments.
4432 if (CE->getNumArgs() < 3)
4433 return;
4434 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4435 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4436 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4437
Nico Weber0e6daef2013-12-26 23:38:39 +00004438 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4439 CE->getRParenLoc()))
4440 return;
4441
Anna Zaks314cd092012-02-01 19:08:57 +00004442 // Identify common expressions, which are wrongly used as the size argument
4443 // to strncat and may lead to buffer overflows.
4444 unsigned PatternType = 0;
4445 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4446 // - sizeof(dst)
4447 if (referToTheSameDecl(SizeOfArg, DstArg))
4448 PatternType = 1;
4449 // - sizeof(src)
4450 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4451 PatternType = 2;
4452 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4453 if (BE->getOpcode() == BO_Sub) {
4454 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4455 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4456 // - sizeof(dst) - strlen(dst)
4457 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4458 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4459 PatternType = 1;
4460 // - sizeof(src) - (anything)
4461 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4462 PatternType = 2;
4463 }
4464 }
4465
4466 if (PatternType == 0)
4467 return;
4468
Anna Zaks5069aa32012-02-03 01:27:37 +00004469 // Generate the diagnostic.
4470 SourceLocation SL = LenArg->getLocStart();
4471 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004472 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004473
4474 // If the function is defined as a builtin macro, do not show macro expansion.
4475 if (SM.isMacroArgExpansion(SL)) {
4476 SL = SM.getSpellingLoc(SL);
4477 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4478 SM.getSpellingLoc(SR.getEnd()));
4479 }
4480
Anna Zaks13b08572012-08-08 21:42:23 +00004481 // Check if the destination is an array (rather than a pointer to an array).
4482 QualType DstTy = DstArg->getType();
4483 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4484 Context);
4485 if (!isKnownSizeArray) {
4486 if (PatternType == 1)
4487 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4488 else
4489 Diag(SL, diag::warn_strncat_src_size) << SR;
4490 return;
4491 }
4492
Anna Zaks314cd092012-02-01 19:08:57 +00004493 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004494 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004495 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004496 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004497
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004498 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004499 llvm::raw_svector_ostream OS(sizeString);
4500 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004501 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004502 OS << ") - ";
4503 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004505 OS << ") - 1";
4506
Anna Zaks5069aa32012-02-03 01:27:37 +00004507 Diag(SL, diag::note_strncat_wrong_size)
4508 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004509}
4510
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004511//===--- CHECK: Return Address of Stack Variable --------------------------===//
4512
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004513static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4514 Decl *ParentDecl);
4515static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4516 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004517
4518/// CheckReturnStackAddr - Check if a return statement returns the address
4519/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004520static void
4521CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4522 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004523
Craig Topperc3ec1492014-05-26 06:22:03 +00004524 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004525 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004526
4527 // Perform checking for returned stack addresses, local blocks,
4528 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004529 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004530 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004531 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004532 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004534 }
4535
Craig Topperc3ec1492014-05-26 06:22:03 +00004536 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004537 return; // Nothing suspicious was found.
4538
4539 SourceLocation diagLoc;
4540 SourceRange diagRange;
4541 if (refVars.empty()) {
4542 diagLoc = stackE->getLocStart();
4543 diagRange = stackE->getSourceRange();
4544 } else {
4545 // We followed through a reference variable. 'stackE' contains the
4546 // problematic expression but we will warn at the return statement pointing
4547 // at the reference variable. We will later display the "trail" of
4548 // reference variables using notes.
4549 diagLoc = refVars[0]->getLocStart();
4550 diagRange = refVars[0]->getSourceRange();
4551 }
4552
4553 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004554 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004555 : diag::warn_ret_stack_addr)
4556 << DR->getDecl()->getDeclName() << diagRange;
4557 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004558 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004559 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004560 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004561 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004562 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4563 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004564 << diagRange;
4565 }
4566
4567 // Display the "trail" of reference variables that we followed until we
4568 // found the problematic expression using notes.
4569 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4570 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4571 // If this var binds to another reference var, show the range of the next
4572 // var, otherwise the var binds to the problematic expression, in which case
4573 // show the range of the expression.
4574 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4575 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004576 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4577 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004578 }
4579}
4580
4581/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4582/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004583/// to a location on the stack, a local block, an address of a label, or a
4584/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004585/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004586/// encounter a subexpression that (1) clearly does not lead to one of the
4587/// above problematic expressions (2) is something we cannot determine leads to
4588/// a problematic expression based on such local checking.
4589///
4590/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4591/// the expression that they point to. Such variables are added to the
4592/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004593///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004594/// EvalAddr processes expressions that are pointers that are used as
4595/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004596/// At the base case of the recursion is a check for the above problematic
4597/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004598///
4599/// This implementation handles:
4600///
4601/// * pointer-to-pointer casts
4602/// * implicit conversions from array references to pointers
4603/// * taking the address of fields
4604/// * arbitrary interplay between "&" and "*" operators
4605/// * pointer arithmetic from an address of a stack variable
4606/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004607static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4608 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004609 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004610 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004611
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004612 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004613 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004614 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004615 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004616 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004617
Peter Collingbourne91147592011-04-15 00:35:48 +00004618 E = E->IgnoreParens();
4619
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004620 // Our "symbolic interpreter" is just a dispatch off the currently
4621 // viewed AST node. We then recursively traverse the AST by calling
4622 // EvalAddr and EvalVal appropriately.
4623 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004624 case Stmt::DeclRefExprClass: {
4625 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4626
Richard Smith40f08eb2014-01-30 22:05:38 +00004627 // If we leave the immediate function, the lifetime isn't about to end.
4628 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004629 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004630
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004631 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4632 // If this is a reference variable, follow through to the expression that
4633 // it points to.
4634 if (V->hasLocalStorage() &&
4635 V->getType()->isReferenceType() && V->hasInit()) {
4636 // Add the reference variable to the "trail".
4637 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004638 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004639 }
4640
Craig Topperc3ec1492014-05-26 06:22:03 +00004641 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004642 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004643
Chris Lattner934edb22007-12-28 05:31:15 +00004644 case Stmt::UnaryOperatorClass: {
4645 // The only unary operator that make sense to handle here
4646 // is AddrOf. All others don't make sense as pointers.
4647 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004648
John McCalle3027922010-08-25 11:45:40 +00004649 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004650 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004651 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004652 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004653 }
Mike Stump11289f42009-09-09 15:08:12 +00004654
Chris Lattner934edb22007-12-28 05:31:15 +00004655 case Stmt::BinaryOperatorClass: {
4656 // Handle pointer arithmetic. All other binary operators are not valid
4657 // in this context.
4658 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004659 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004660
John McCalle3027922010-08-25 11:45:40 +00004661 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004662 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004663
Chris Lattner934edb22007-12-28 05:31:15 +00004664 Expr *Base = B->getLHS();
4665
4666 // Determine which argument is the real pointer base. It could be
4667 // the RHS argument instead of the LHS.
4668 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004669
Chris Lattner934edb22007-12-28 05:31:15 +00004670 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004671 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004672 }
Steve Naroff2752a172008-09-10 19:17:48 +00004673
Chris Lattner934edb22007-12-28 05:31:15 +00004674 // For conditional operators we need to see if either the LHS or RHS are
4675 // valid DeclRefExpr*s. If one of them is valid, we return it.
4676 case Stmt::ConditionalOperatorClass: {
4677 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004678
Chris Lattner934edb22007-12-28 05:31:15 +00004679 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004680 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4681 if (Expr *LHSExpr = C->getLHS()) {
4682 // In C++, we can have a throw-expression, which has 'void' type.
4683 if (!LHSExpr->getType()->isVoidType())
4684 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004685 return LHS;
4686 }
Chris Lattner934edb22007-12-28 05:31:15 +00004687
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004688 // In C++, we can have a throw-expression, which has 'void' type.
4689 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004690 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004691
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004692 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004693 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004694
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004695 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004696 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004697 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004698 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004699
4700 case Stmt::AddrLabelExprClass:
4701 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004702
John McCall28fc7092011-11-10 05:35:25 +00004703 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004704 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4705 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004706
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004707 // For casts, we need to handle conversions from arrays to
4708 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004709 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004710 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004711 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004712 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004713 case Stmt::CXXStaticCastExprClass:
4714 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004715 case Stmt::CXXConstCastExprClass:
4716 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004717 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4718 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004719 case CK_LValueToRValue:
4720 case CK_NoOp:
4721 case CK_BaseToDerived:
4722 case CK_DerivedToBase:
4723 case CK_UncheckedDerivedToBase:
4724 case CK_Dynamic:
4725 case CK_CPointerToObjCPointerCast:
4726 case CK_BlockPointerToObjCPointerCast:
4727 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004728 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004729
4730 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004731 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004732
Richard Trieudadefde2014-07-02 04:39:38 +00004733 case CK_BitCast:
4734 if (SubExpr->getType()->isAnyPointerType() ||
4735 SubExpr->getType()->isBlockPointerType() ||
4736 SubExpr->getType()->isObjCQualifiedIdType())
4737 return EvalAddr(SubExpr, refVars, ParentDecl);
4738 else
4739 return nullptr;
4740
Eli Friedman8195ad72012-02-23 23:04:32 +00004741 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004742 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004743 }
Chris Lattner934edb22007-12-28 05:31:15 +00004744 }
Mike Stump11289f42009-09-09 15:08:12 +00004745
Douglas Gregorfe314812011-06-21 17:03:29 +00004746 case Stmt::MaterializeTemporaryExprClass:
4747 if (Expr *Result = EvalAddr(
4748 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004749 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004750 return Result;
4751
4752 return E;
4753
Chris Lattner934edb22007-12-28 05:31:15 +00004754 // Everything else: we simply don't reason about them.
4755 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004756 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004757 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004758}
Mike Stump11289f42009-09-09 15:08:12 +00004759
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004760
4761/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4762/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004763static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4764 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004765do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004766 // We should only be called for evaluating non-pointer expressions, or
4767 // expressions with a pointer type that are not used as references but instead
4768 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004769
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004770 // Our "symbolic interpreter" is just a dispatch off the currently
4771 // viewed AST node. We then recursively traverse the AST by calling
4772 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004773
4774 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004775 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004776 case Stmt::ImplicitCastExprClass: {
4777 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004778 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004779 E = IE->getSubExpr();
4780 continue;
4781 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004782 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004783 }
4784
John McCall28fc7092011-11-10 05:35:25 +00004785 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004786 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004787
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004788 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004789 // When we hit a DeclRefExpr we are looking at code that refers to a
4790 // variable's name. If it's not a reference variable we check if it has
4791 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004792 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004793
Richard Smith40f08eb2014-01-30 22:05:38 +00004794 // If we leave the immediate function, the lifetime isn't about to end.
4795 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004796 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004797
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004798 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4799 // Check if it refers to itself, e.g. "int& i = i;".
4800 if (V == ParentDecl)
4801 return DR;
4802
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004803 if (V->hasLocalStorage()) {
4804 if (!V->getType()->isReferenceType())
4805 return DR;
4806
4807 // Reference variable, follow through to the expression that
4808 // it points to.
4809 if (V->hasInit()) {
4810 // Add the reference variable to the "trail".
4811 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004812 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004813 }
4814 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004815 }
Mike Stump11289f42009-09-09 15:08:12 +00004816
Craig Topperc3ec1492014-05-26 06:22:03 +00004817 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004818 }
Mike Stump11289f42009-09-09 15:08:12 +00004819
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004820 case Stmt::UnaryOperatorClass: {
4821 // The only unary operator that make sense to handle here
4822 // is Deref. All others don't resolve to a "name." This includes
4823 // handling all sorts of rvalues passed to a unary operator.
4824 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004825
John McCalle3027922010-08-25 11:45:40 +00004826 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004827 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004828
Craig Topperc3ec1492014-05-26 06:22:03 +00004829 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004830 }
Mike Stump11289f42009-09-09 15:08:12 +00004831
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004832 case Stmt::ArraySubscriptExprClass: {
4833 // Array subscripts are potential references to data on the stack. We
4834 // retrieve the DeclRefExpr* for the array variable if it indeed
4835 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004836 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004837 }
Mike Stump11289f42009-09-09 15:08:12 +00004838
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004839 case Stmt::ConditionalOperatorClass: {
4840 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004841 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004842 ConditionalOperator *C = cast<ConditionalOperator>(E);
4843
Anders Carlsson801c5c72007-11-30 19:04:31 +00004844 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004845 if (Expr *LHSExpr = C->getLHS()) {
4846 // In C++, we can have a throw-expression, which has 'void' type.
4847 if (!LHSExpr->getType()->isVoidType())
4848 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4849 return LHS;
4850 }
4851
4852 // In C++, we can have a throw-expression, which has 'void' type.
4853 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004854 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004855
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004856 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004857 }
Mike Stump11289f42009-09-09 15:08:12 +00004858
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004859 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004860 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004861 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004862
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004863 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004864 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004865 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004866
4867 // Check whether the member type is itself a reference, in which case
4868 // we're not going to refer to the member, but to what the member refers to.
4869 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004870 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004871
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004872 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004873 }
Mike Stump11289f42009-09-09 15:08:12 +00004874
Douglas Gregorfe314812011-06-21 17:03:29 +00004875 case Stmt::MaterializeTemporaryExprClass:
4876 if (Expr *Result = EvalVal(
4877 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004878 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004879 return Result;
4880
4881 return E;
4882
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004883 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004884 // Check that we don't return or take the address of a reference to a
4885 // temporary. This is only useful in C++.
4886 if (!E->isTypeDependent() && E->isRValue())
4887 return E;
4888
4889 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004890 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004891 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004892} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004893}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004894
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004895void
4896Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4897 SourceLocation ReturnLoc,
4898 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004899 const AttrVec *Attrs,
4900 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004901 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4902
4903 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004904 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4905 CheckNonNullExpr(*this, RetValExp))
4906 Diag(ReturnLoc, diag::warn_null_ret)
4907 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004908
4909 // C++11 [basic.stc.dynamic.allocation]p4:
4910 // If an allocation function declared with a non-throwing
4911 // exception-specification fails to allocate storage, it shall return
4912 // a null pointer. Any other allocation function that fails to allocate
4913 // storage shall indicate failure only by throwing an exception [...]
4914 if (FD) {
4915 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4916 if (Op == OO_New || Op == OO_Array_New) {
4917 const FunctionProtoType *Proto
4918 = FD->getType()->castAs<FunctionProtoType>();
4919 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4920 CheckNonNullExpr(*this, RetValExp))
4921 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4922 << FD << getLangOpts().CPlusPlus11;
4923 }
4924 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004925}
4926
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004927//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4928
4929/// Check for comparisons of floating point operands using != and ==.
4930/// Issue a warning if these are no self-comparisons, as they are not likely
4931/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004932void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004933 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4934 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004935
4936 // Special case: check for x == x (which is OK).
4937 // Do not emit warnings for such cases.
4938 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4939 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4940 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004941 return;
Mike Stump11289f42009-09-09 15:08:12 +00004942
4943
Ted Kremenekeda40e22007-11-29 00:59:04 +00004944 // Special case: check for comparisons against literals that can be exactly
4945 // represented by APFloat. In such cases, do not emit a warning. This
4946 // is a heuristic: often comparison against such literals are used to
4947 // detect if a value in a variable has not changed. This clearly can
4948 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004949 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4950 if (FLL->isExact())
4951 return;
4952 } else
4953 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4954 if (FLR->isExact())
4955 return;
Mike Stump11289f42009-09-09 15:08:12 +00004956
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004957 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004958 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004959 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004960 return;
Mike Stump11289f42009-09-09 15:08:12 +00004961
David Blaikie1f4ff152012-07-16 20:47:22 +00004962 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004963 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004964 return;
Mike Stump11289f42009-09-09 15:08:12 +00004965
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004966 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004967 Diag(Loc, diag::warn_floatingpoint_eq)
4968 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004969}
John McCallca01b222010-01-04 23:21:16 +00004970
John McCall70aa5392010-01-06 05:24:50 +00004971//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4972//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004973
John McCall70aa5392010-01-06 05:24:50 +00004974namespace {
John McCallca01b222010-01-04 23:21:16 +00004975
John McCall70aa5392010-01-06 05:24:50 +00004976/// Structure recording the 'active' range of an integer-valued
4977/// expression.
4978struct IntRange {
4979 /// The number of bits active in the int.
4980 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004981
John McCall70aa5392010-01-06 05:24:50 +00004982 /// True if the int is known not to have negative values.
4983 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004984
John McCall70aa5392010-01-06 05:24:50 +00004985 IntRange(unsigned Width, bool NonNegative)
4986 : Width(Width), NonNegative(NonNegative)
4987 {}
John McCallca01b222010-01-04 23:21:16 +00004988
John McCall817d4af2010-11-10 23:38:19 +00004989 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004990 static IntRange forBoolType() {
4991 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004992 }
4993
John McCall817d4af2010-11-10 23:38:19 +00004994 /// Returns the range of an opaque value of the given integral type.
4995 static IntRange forValueOfType(ASTContext &C, QualType T) {
4996 return forValueOfCanonicalType(C,
4997 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004998 }
4999
John McCall817d4af2010-11-10 23:38:19 +00005000 /// Returns the range of an opaque value of a canonical integral type.
5001 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005002 assert(T->isCanonicalUnqualified());
5003
5004 if (const VectorType *VT = dyn_cast<VectorType>(T))
5005 T = VT->getElementType().getTypePtr();
5006 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5007 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005008 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5009 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005010
David Majnemer6a426652013-06-07 22:07:20 +00005011 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005012 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005013 EnumDecl *Enum = ET->getDecl();
5014 if (!Enum->isCompleteDefinition())
5015 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005016
David Majnemer6a426652013-06-07 22:07:20 +00005017 unsigned NumPositive = Enum->getNumPositiveBits();
5018 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005019
David Majnemer6a426652013-06-07 22:07:20 +00005020 if (NumNegative == 0)
5021 return IntRange(NumPositive, true/*NonNegative*/);
5022 else
5023 return IntRange(std::max(NumPositive + 1, NumNegative),
5024 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005025 }
John McCall70aa5392010-01-06 05:24:50 +00005026
5027 const BuiltinType *BT = cast<BuiltinType>(T);
5028 assert(BT->isInteger());
5029
5030 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5031 }
5032
John McCall817d4af2010-11-10 23:38:19 +00005033 /// Returns the "target" range of a canonical integral type, i.e.
5034 /// the range of values expressible in the type.
5035 ///
5036 /// This matches forValueOfCanonicalType except that enums have the
5037 /// full range of their type, not the range of their enumerators.
5038 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5039 assert(T->isCanonicalUnqualified());
5040
5041 if (const VectorType *VT = dyn_cast<VectorType>(T))
5042 T = VT->getElementType().getTypePtr();
5043 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5044 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005045 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5046 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005047 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005048 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005049
5050 const BuiltinType *BT = cast<BuiltinType>(T);
5051 assert(BT->isInteger());
5052
5053 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5054 }
5055
5056 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005057 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005058 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005059 L.NonNegative && R.NonNegative);
5060 }
5061
John McCall817d4af2010-11-10 23:38:19 +00005062 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005063 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005064 return IntRange(std::min(L.Width, R.Width),
5065 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005066 }
5067};
5068
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005069static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5070 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005071 if (value.isSigned() && value.isNegative())
5072 return IntRange(value.getMinSignedBits(), false);
5073
5074 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005075 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005076
5077 // isNonNegative() just checks the sign bit without considering
5078 // signedness.
5079 return IntRange(value.getActiveBits(), true);
5080}
5081
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005082static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5083 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005084 if (result.isInt())
5085 return GetValueRange(C, result.getInt(), MaxWidth);
5086
5087 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005088 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5089 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5090 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5091 R = IntRange::join(R, El);
5092 }
John McCall70aa5392010-01-06 05:24:50 +00005093 return R;
5094 }
5095
5096 if (result.isComplexInt()) {
5097 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5098 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5099 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005100 }
5101
5102 // This can happen with lossless casts to intptr_t of "based" lvalues.
5103 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005104 // FIXME: The only reason we need to pass the type in here is to get
5105 // the sign right on this one case. It would be nice if APValue
5106 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005107 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005108 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005109}
John McCall70aa5392010-01-06 05:24:50 +00005110
Eli Friedmane6d33952013-07-08 20:20:06 +00005111static QualType GetExprType(Expr *E) {
5112 QualType Ty = E->getType();
5113 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5114 Ty = AtomicRHS->getValueType();
5115 return Ty;
5116}
5117
John McCall70aa5392010-01-06 05:24:50 +00005118/// Pseudo-evaluate the given integer expression, estimating the
5119/// range of values it might take.
5120///
5121/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005122static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005123 E = E->IgnoreParens();
5124
5125 // Try a full evaluation first.
5126 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005127 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005128 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005129
5130 // I think we only want to look through implicit casts here; if the
5131 // user has an explicit widening cast, we should treat the value as
5132 // being of the new, wider type.
5133 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005134 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005135 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5136
Eli Friedmane6d33952013-07-08 20:20:06 +00005137 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005138
John McCalle3027922010-08-25 11:45:40 +00005139 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005140
John McCall70aa5392010-01-06 05:24:50 +00005141 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005142 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005143 return OutputTypeRange;
5144
5145 IntRange SubRange
5146 = GetExprRange(C, CE->getSubExpr(),
5147 std::min(MaxWidth, OutputTypeRange.Width));
5148
5149 // Bail out if the subexpr's range is as wide as the cast type.
5150 if (SubRange.Width >= OutputTypeRange.Width)
5151 return OutputTypeRange;
5152
5153 // Otherwise, we take the smaller width, and we're non-negative if
5154 // either the output type or the subexpr is.
5155 return IntRange(SubRange.Width,
5156 SubRange.NonNegative || OutputTypeRange.NonNegative);
5157 }
5158
5159 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5160 // If we can fold the condition, just take that operand.
5161 bool CondResult;
5162 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5163 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5164 : CO->getFalseExpr(),
5165 MaxWidth);
5166
5167 // Otherwise, conservatively merge.
5168 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5169 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5170 return IntRange::join(L, R);
5171 }
5172
5173 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5174 switch (BO->getOpcode()) {
5175
5176 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005177 case BO_LAnd:
5178 case BO_LOr:
5179 case BO_LT:
5180 case BO_GT:
5181 case BO_LE:
5182 case BO_GE:
5183 case BO_EQ:
5184 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005185 return IntRange::forBoolType();
5186
John McCallc3688382011-07-13 06:35:24 +00005187 // The type of the assignments is the type of the LHS, so the RHS
5188 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005189 case BO_MulAssign:
5190 case BO_DivAssign:
5191 case BO_RemAssign:
5192 case BO_AddAssign:
5193 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005194 case BO_XorAssign:
5195 case BO_OrAssign:
5196 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005197 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005198
John McCallc3688382011-07-13 06:35:24 +00005199 // Simple assignments just pass through the RHS, which will have
5200 // been coerced to the LHS type.
5201 case BO_Assign:
5202 // TODO: bitfields?
5203 return GetExprRange(C, BO->getRHS(), MaxWidth);
5204
John McCall70aa5392010-01-06 05:24:50 +00005205 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005206 case BO_PtrMemD:
5207 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005208 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005209
John McCall2ce81ad2010-01-06 22:07:33 +00005210 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005211 case BO_And:
5212 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005213 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5214 GetExprRange(C, BO->getRHS(), MaxWidth));
5215
John McCall70aa5392010-01-06 05:24:50 +00005216 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005217 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005218 // ...except that we want to treat '1 << (blah)' as logically
5219 // positive. It's an important idiom.
5220 if (IntegerLiteral *I
5221 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5222 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005223 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005224 return IntRange(R.Width, /*NonNegative*/ true);
5225 }
5226 }
5227 // fallthrough
5228
John McCalle3027922010-08-25 11:45:40 +00005229 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005230 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005231
John McCall2ce81ad2010-01-06 22:07:33 +00005232 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005233 case BO_Shr:
5234 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005235 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5236
5237 // If the shift amount is a positive constant, drop the width by
5238 // that much.
5239 llvm::APSInt shift;
5240 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5241 shift.isNonNegative()) {
5242 unsigned zext = shift.getZExtValue();
5243 if (zext >= L.Width)
5244 L.Width = (L.NonNegative ? 0 : 1);
5245 else
5246 L.Width -= zext;
5247 }
5248
5249 return L;
5250 }
5251
5252 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005253 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005254 return GetExprRange(C, BO->getRHS(), MaxWidth);
5255
John McCall2ce81ad2010-01-06 22:07:33 +00005256 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005257 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005258 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005259 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005260 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005261
John McCall51431812011-07-14 22:39:48 +00005262 // The width of a division result is mostly determined by the size
5263 // of the LHS.
5264 case BO_Div: {
5265 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005266 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005267 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5268
5269 // If the divisor is constant, use that.
5270 llvm::APSInt divisor;
5271 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5272 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5273 if (log2 >= L.Width)
5274 L.Width = (L.NonNegative ? 0 : 1);
5275 else
5276 L.Width = std::min(L.Width - log2, MaxWidth);
5277 return L;
5278 }
5279
5280 // Otherwise, just use the LHS's width.
5281 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5282 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5283 }
5284
5285 // The result of a remainder can't be larger than the result of
5286 // either side.
5287 case BO_Rem: {
5288 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005289 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005290 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5291 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5292
5293 IntRange meet = IntRange::meet(L, R);
5294 meet.Width = std::min(meet.Width, MaxWidth);
5295 return meet;
5296 }
5297
5298 // The default behavior is okay for these.
5299 case BO_Mul:
5300 case BO_Add:
5301 case BO_Xor:
5302 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005303 break;
5304 }
5305
John McCall51431812011-07-14 22:39:48 +00005306 // The default case is to treat the operation as if it were closed
5307 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005308 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5309 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5310 return IntRange::join(L, R);
5311 }
5312
5313 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5314 switch (UO->getOpcode()) {
5315 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005316 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005317 return IntRange::forBoolType();
5318
5319 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005320 case UO_Deref:
5321 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005322 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005323
5324 default:
5325 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5326 }
5327 }
5328
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005329 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5330 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5331
John McCalld25db7e2013-05-06 21:39:12 +00005332 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005333 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005334 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005335
Eli Friedmane6d33952013-07-08 20:20:06 +00005336 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005337}
John McCall263a48b2010-01-04 23:31:57 +00005338
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005339static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005340 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005341}
5342
John McCall263a48b2010-01-04 23:31:57 +00005343/// Checks whether the given value, which currently has the given
5344/// source semantics, has the same value when coerced through the
5345/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005346static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5347 const llvm::fltSemantics &Src,
5348 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005349 llvm::APFloat truncated = value;
5350
5351 bool ignored;
5352 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5353 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5354
5355 return truncated.bitwiseIsEqual(value);
5356}
5357
5358/// Checks whether the given value, which currently has the given
5359/// source semantics, has the same value when coerced through the
5360/// target semantics.
5361///
5362/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005363static bool IsSameFloatAfterCast(const APValue &value,
5364 const llvm::fltSemantics &Src,
5365 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005366 if (value.isFloat())
5367 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5368
5369 if (value.isVector()) {
5370 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5371 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5372 return false;
5373 return true;
5374 }
5375
5376 assert(value.isComplexFloat());
5377 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5378 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5379}
5380
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005381static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005382
Ted Kremenek6274be42010-09-23 21:43:44 +00005383static bool IsZero(Sema &S, Expr *E) {
5384 // Suppress cases where we are comparing against an enum constant.
5385 if (const DeclRefExpr *DR =
5386 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5387 if (isa<EnumConstantDecl>(DR->getDecl()))
5388 return false;
5389
5390 // Suppress cases where the '0' value is expanded from a macro.
5391 if (E->getLocStart().isMacroID())
5392 return false;
5393
John McCallcc7e5bf2010-05-06 08:58:33 +00005394 llvm::APSInt Value;
5395 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5396}
5397
John McCall2551c1b2010-10-06 00:25:24 +00005398static bool HasEnumType(Expr *E) {
5399 // Strip off implicit integral promotions.
5400 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005401 if (ICE->getCastKind() != CK_IntegralCast &&
5402 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005403 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005404 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005405 }
5406
5407 return E->getType()->isEnumeralType();
5408}
5409
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005410static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005411 // Disable warning in template instantiations.
5412 if (!S.ActiveTemplateInstantiations.empty())
5413 return;
5414
John McCalle3027922010-08-25 11:45:40 +00005415 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005416 if (E->isValueDependent())
5417 return;
5418
John McCalle3027922010-08-25 11:45:40 +00005419 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005420 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005421 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005423 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005424 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005425 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005427 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005428 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005429 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005431 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005432 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005433 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5435 }
5436}
5437
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005438static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005439 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005440 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005441 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005442 // Disable warning in template instantiations.
5443 if (!S.ActiveTemplateInstantiations.empty())
5444 return;
5445
Richard Trieu0f097742014-04-04 04:13:47 +00005446 // TODO: Investigate using GetExprRange() to get tighter bounds
5447 // on the bit ranges.
5448 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005449 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5450 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005451 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5452 unsigned OtherWidth = OtherRange.Width;
5453
5454 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5455
Richard Trieu560910c2012-11-14 22:50:24 +00005456 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005457 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005458 return;
5459
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005460 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005461 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005462
Richard Trieu0f097742014-04-04 04:13:47 +00005463 // Used for diagnostic printout.
5464 enum {
5465 LiteralConstant = 0,
5466 CXXBoolLiteralTrue,
5467 CXXBoolLiteralFalse
5468 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005469
Richard Trieu0f097742014-04-04 04:13:47 +00005470 if (!OtherIsBooleanType) {
5471 QualType ConstantT = Constant->getType();
5472 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005473
Richard Trieu0f097742014-04-04 04:13:47 +00005474 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5475 return;
5476 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5477 "comparison with non-integer type");
5478
5479 bool ConstantSigned = ConstantT->isSignedIntegerType();
5480 bool CommonSigned = CommonT->isSignedIntegerType();
5481
5482 bool EqualityOnly = false;
5483
5484 if (CommonSigned) {
5485 // The common type is signed, therefore no signed to unsigned conversion.
5486 if (!OtherRange.NonNegative) {
5487 // Check that the constant is representable in type OtherT.
5488 if (ConstantSigned) {
5489 if (OtherWidth >= Value.getMinSignedBits())
5490 return;
5491 } else { // !ConstantSigned
5492 if (OtherWidth >= Value.getActiveBits() + 1)
5493 return;
5494 }
5495 } else { // !OtherSigned
5496 // Check that the constant is representable in type OtherT.
5497 // Negative values are out of range.
5498 if (ConstantSigned) {
5499 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5500 return;
5501 } else { // !ConstantSigned
5502 if (OtherWidth >= Value.getActiveBits())
5503 return;
5504 }
Richard Trieu560910c2012-11-14 22:50:24 +00005505 }
Richard Trieu0f097742014-04-04 04:13:47 +00005506 } else { // !CommonSigned
5507 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005508 if (OtherWidth >= Value.getActiveBits())
5509 return;
Craig Toppercf360162014-06-18 05:13:11 +00005510 } else { // OtherSigned
5511 assert(!ConstantSigned &&
5512 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005513 // Check to see if the constant is representable in OtherT.
5514 if (OtherWidth > Value.getActiveBits())
5515 return;
5516 // Check to see if the constant is equivalent to a negative value
5517 // cast to CommonT.
5518 if (S.Context.getIntWidth(ConstantT) ==
5519 S.Context.getIntWidth(CommonT) &&
5520 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5521 return;
5522 // The constant value rests between values that OtherT can represent
5523 // after conversion. Relational comparison still works, but equality
5524 // comparisons will be tautological.
5525 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005526 }
5527 }
Richard Trieu0f097742014-04-04 04:13:47 +00005528
5529 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5530
5531 if (op == BO_EQ || op == BO_NE) {
5532 IsTrue = op == BO_NE;
5533 } else if (EqualityOnly) {
5534 return;
5535 } else if (RhsConstant) {
5536 if (op == BO_GT || op == BO_GE)
5537 IsTrue = !PositiveConstant;
5538 else // op == BO_LT || op == BO_LE
5539 IsTrue = PositiveConstant;
5540 } else {
5541 if (op == BO_LT || op == BO_LE)
5542 IsTrue = !PositiveConstant;
5543 else // op == BO_GT || op == BO_GE
5544 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005545 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005546 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005547 // Other isKnownToHaveBooleanValue
5548 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5549 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5550 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5551
5552 static const struct LinkedConditions {
5553 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5554 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5555 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5556 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5557 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5558 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5559
5560 } TruthTable = {
5561 // Constant on LHS. | Constant on RHS. |
5562 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5563 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5564 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5565 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5566 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5567 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5568 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5569 };
5570
5571 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5572
5573 enum ConstantValue ConstVal = Zero;
5574 if (Value.isUnsigned() || Value.isNonNegative()) {
5575 if (Value == 0) {
5576 LiteralOrBoolConstant =
5577 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5578 ConstVal = Zero;
5579 } else if (Value == 1) {
5580 LiteralOrBoolConstant =
5581 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5582 ConstVal = One;
5583 } else {
5584 LiteralOrBoolConstant = LiteralConstant;
5585 ConstVal = GT_One;
5586 }
5587 } else {
5588 ConstVal = LT_Zero;
5589 }
5590
5591 CompareBoolWithConstantResult CmpRes;
5592
5593 switch (op) {
5594 case BO_LT:
5595 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5596 break;
5597 case BO_GT:
5598 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5599 break;
5600 case BO_LE:
5601 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5602 break;
5603 case BO_GE:
5604 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5605 break;
5606 case BO_EQ:
5607 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5608 break;
5609 case BO_NE:
5610 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5611 break;
5612 default:
5613 CmpRes = Unkwn;
5614 break;
5615 }
5616
5617 if (CmpRes == AFals) {
5618 IsTrue = false;
5619 } else if (CmpRes == ATrue) {
5620 IsTrue = true;
5621 } else {
5622 return;
5623 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005624 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005625
5626 // If this is a comparison to an enum constant, include that
5627 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005628 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005629 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5630 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5631
5632 SmallString<64> PrettySourceValue;
5633 llvm::raw_svector_ostream OS(PrettySourceValue);
5634 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005635 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005636 else
5637 OS << Value;
5638
Richard Trieu0f097742014-04-04 04:13:47 +00005639 S.DiagRuntimeBehavior(
5640 E->getOperatorLoc(), E,
5641 S.PDiag(diag::warn_out_of_range_compare)
5642 << OS.str() << LiteralOrBoolConstant
5643 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5644 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005645}
5646
John McCallcc7e5bf2010-05-06 08:58:33 +00005647/// Analyze the operands of the given comparison. Implements the
5648/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005649static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005650 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5651 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005652}
John McCall263a48b2010-01-04 23:31:57 +00005653
John McCallca01b222010-01-04 23:21:16 +00005654/// \brief Implements -Wsign-compare.
5655///
Richard Trieu82402a02011-09-15 21:56:47 +00005656/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005657static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005658 // The type the comparison is being performed in.
5659 QualType T = E->getLHS()->getType();
5660 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5661 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005662 if (E->isValueDependent())
5663 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005664
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005665 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5666 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005667
5668 bool IsComparisonConstant = false;
5669
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005670 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005671 // of 'true' or 'false'.
5672 if (T->isIntegralType(S.Context)) {
5673 llvm::APSInt RHSValue;
5674 bool IsRHSIntegralLiteral =
5675 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5676 llvm::APSInt LHSValue;
5677 bool IsLHSIntegralLiteral =
5678 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5679 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5680 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5681 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5682 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5683 else
5684 IsComparisonConstant =
5685 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005686 } else if (!T->hasUnsignedIntegerRepresentation())
5687 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005688
John McCallcc7e5bf2010-05-06 08:58:33 +00005689 // We don't do anything special if this isn't an unsigned integral
5690 // comparison: we're only interested in integral comparisons, and
5691 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005692 //
5693 // We also don't care about value-dependent expressions or expressions
5694 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005695 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005696 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005697
John McCallcc7e5bf2010-05-06 08:58:33 +00005698 // Check to see if one of the (unmodified) operands is of different
5699 // signedness.
5700 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005701 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5702 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005703 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005704 signedOperand = LHS;
5705 unsignedOperand = RHS;
5706 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5707 signedOperand = RHS;
5708 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005709 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005710 CheckTrivialUnsignedComparison(S, E);
5711 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005712 }
5713
John McCallcc7e5bf2010-05-06 08:58:33 +00005714 // Otherwise, calculate the effective range of the signed operand.
5715 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005716
John McCallcc7e5bf2010-05-06 08:58:33 +00005717 // Go ahead and analyze implicit conversions in the operands. Note
5718 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005719 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5720 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005721
John McCallcc7e5bf2010-05-06 08:58:33 +00005722 // If the signed range is non-negative, -Wsign-compare won't fire,
5723 // but we should still check for comparisons which are always true
5724 // or false.
5725 if (signedRange.NonNegative)
5726 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005727
5728 // For (in)equality comparisons, if the unsigned operand is a
5729 // constant which cannot collide with a overflowed signed operand,
5730 // then reinterpreting the signed operand as unsigned will not
5731 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005732 if (E->isEqualityOp()) {
5733 unsigned comparisonWidth = S.Context.getIntWidth(T);
5734 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005735
John McCallcc7e5bf2010-05-06 08:58:33 +00005736 // We should never be unable to prove that the unsigned operand is
5737 // non-negative.
5738 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5739
5740 if (unsignedRange.Width < comparisonWidth)
5741 return;
5742 }
5743
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005744 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5745 S.PDiag(diag::warn_mixed_sign_comparison)
5746 << LHS->getType() << RHS->getType()
5747 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005748}
5749
John McCall1f425642010-11-11 03:21:53 +00005750/// Analyzes an attempt to assign the given value to a bitfield.
5751///
5752/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005753static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5754 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005755 assert(Bitfield->isBitField());
5756 if (Bitfield->isInvalidDecl())
5757 return false;
5758
John McCalldeebbcf2010-11-11 05:33:51 +00005759 // White-list bool bitfields.
5760 if (Bitfield->getType()->isBooleanType())
5761 return false;
5762
Douglas Gregor789adec2011-02-04 13:09:01 +00005763 // Ignore value- or type-dependent expressions.
5764 if (Bitfield->getBitWidth()->isValueDependent() ||
5765 Bitfield->getBitWidth()->isTypeDependent() ||
5766 Init->isValueDependent() ||
5767 Init->isTypeDependent())
5768 return false;
5769
John McCall1f425642010-11-11 03:21:53 +00005770 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5771
Richard Smith5fab0c92011-12-28 19:48:30 +00005772 llvm::APSInt Value;
5773 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005774 return false;
5775
John McCall1f425642010-11-11 03:21:53 +00005776 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005777 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005778
5779 if (OriginalWidth <= FieldWidth)
5780 return false;
5781
Eli Friedmanc267a322012-01-26 23:11:39 +00005782 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005783 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005784 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005785
Eli Friedmanc267a322012-01-26 23:11:39 +00005786 // Check whether the stored value is equal to the original value.
5787 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005788 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005789 return false;
5790
Eli Friedmanc267a322012-01-26 23:11:39 +00005791 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005792 // therefore don't strictly fit into a signed bitfield of width 1.
5793 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005794 return false;
5795
John McCall1f425642010-11-11 03:21:53 +00005796 std::string PrettyValue = Value.toString(10);
5797 std::string PrettyTrunc = TruncatedValue.toString(10);
5798
5799 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5800 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5801 << Init->getSourceRange();
5802
5803 return true;
5804}
5805
John McCalld2a53122010-11-09 23:24:47 +00005806/// Analyze the given simple or compound assignment for warning-worthy
5807/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005808static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005809 // Just recurse on the LHS.
5810 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5811
5812 // We want to recurse on the RHS as normal unless we're assigning to
5813 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005814 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005815 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005816 E->getOperatorLoc())) {
5817 // Recurse, ignoring any implicit conversions on the RHS.
5818 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5819 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005820 }
5821 }
5822
5823 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5824}
5825
John McCall263a48b2010-01-04 23:31:57 +00005826/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005827static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005828 SourceLocation CContext, unsigned diag,
5829 bool pruneControlFlow = false) {
5830 if (pruneControlFlow) {
5831 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5832 S.PDiag(diag)
5833 << SourceType << T << E->getSourceRange()
5834 << SourceRange(CContext));
5835 return;
5836 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005837 S.Diag(E->getExprLoc(), diag)
5838 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5839}
5840
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005841/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005842static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005843 SourceLocation CContext, unsigned diag,
5844 bool pruneControlFlow = false) {
5845 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005846}
5847
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005848/// Diagnose an implicit cast from a literal expression. Does not warn when the
5849/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005850void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5851 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005852 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005853 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005854 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005855 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5856 T->hasUnsignedIntegerRepresentation());
5857 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005858 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005859 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005860 return;
5861
Eli Friedman07185912013-08-29 23:44:43 +00005862 // FIXME: Force the precision of the source value down so we don't print
5863 // digits which are usually useless (we don't really care here if we
5864 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5865 // would automatically print the shortest representation, but it's a bit
5866 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005867 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005868 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5869 precision = (precision * 59 + 195) / 196;
5870 Value.toString(PrettySourceValue, precision);
5871
David Blaikie9b88cc02012-05-15 17:18:27 +00005872 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005873 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5874 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5875 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005876 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005877
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005878 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005879 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5880 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005881}
5882
John McCall18a2c2c2010-11-09 22:22:12 +00005883std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5884 if (!Range.Width) return "0";
5885
5886 llvm::APSInt ValueInRange = Value;
5887 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005888 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005889 return ValueInRange.toString(10);
5890}
5891
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005892static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5893 if (!isa<ImplicitCastExpr>(Ex))
5894 return false;
5895
5896 Expr *InnerE = Ex->IgnoreParenImpCasts();
5897 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5898 const Type *Source =
5899 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5900 if (Target->isDependentType())
5901 return false;
5902
5903 const BuiltinType *FloatCandidateBT =
5904 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5905 const Type *BoolCandidateType = ToBool ? Target : Source;
5906
5907 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5908 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5909}
5910
5911void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5912 SourceLocation CC) {
5913 unsigned NumArgs = TheCall->getNumArgs();
5914 for (unsigned i = 0; i < NumArgs; ++i) {
5915 Expr *CurrA = TheCall->getArg(i);
5916 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5917 continue;
5918
5919 bool IsSwapped = ((i > 0) &&
5920 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5921 IsSwapped |= ((i < (NumArgs - 1)) &&
5922 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5923 if (IsSwapped) {
5924 // Warn on this floating-point to bool conversion.
5925 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5926 CurrA->getType(), CC,
5927 diag::warn_impcast_floating_point_to_bool);
5928 }
5929 }
5930}
5931
John McCallcc7e5bf2010-05-06 08:58:33 +00005932void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005933 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005934 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005935
John McCallcc7e5bf2010-05-06 08:58:33 +00005936 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5937 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5938 if (Source == Target) return;
5939 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005940
Chandler Carruthc22845a2011-07-26 05:40:03 +00005941 // If the conversion context location is invalid don't complain. We also
5942 // don't want to emit a warning if the issue occurs from the expansion of
5943 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5944 // delay this check as long as possible. Once we detect we are in that
5945 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005946 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005947 return;
5948
Richard Trieu021baa32011-09-23 20:10:00 +00005949 // Diagnose implicit casts to bool.
5950 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5951 if (isa<StringLiteral>(E))
5952 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005953 // and expressions, for instance, assert(0 && "error here"), are
5954 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005955 return DiagnoseImpCast(S, E, T, CC,
5956 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005957 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5958 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5959 // This covers the literal expressions that evaluate to Objective-C
5960 // objects.
5961 return DiagnoseImpCast(S, E, T, CC,
5962 diag::warn_impcast_objective_c_literal_to_bool);
5963 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005964 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5965 // Warn on pointer to bool conversion that is always true.
5966 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5967 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005968 }
Richard Trieu021baa32011-09-23 20:10:00 +00005969 }
John McCall263a48b2010-01-04 23:31:57 +00005970
5971 // Strip vector types.
5972 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005973 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005974 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005975 return;
John McCallacf0ee52010-10-08 02:01:28 +00005976 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005977 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005978
5979 // If the vector cast is cast between two vectors of the same size, it is
5980 // a bitcast, not a conversion.
5981 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5982 return;
John McCall263a48b2010-01-04 23:31:57 +00005983
5984 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5985 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5986 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005987 if (auto VecTy = dyn_cast<VectorType>(Target))
5988 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005989
5990 // Strip complex types.
5991 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005992 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005993 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005994 return;
5995
John McCallacf0ee52010-10-08 02:01:28 +00005996 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005997 }
John McCall263a48b2010-01-04 23:31:57 +00005998
5999 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6000 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6001 }
6002
6003 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6004 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6005
6006 // If the source is floating point...
6007 if (SourceBT && SourceBT->isFloatingPoint()) {
6008 // ...and the target is floating point...
6009 if (TargetBT && TargetBT->isFloatingPoint()) {
6010 // ...then warn if we're dropping FP rank.
6011
6012 // Builtin FP kinds are ordered by increasing FP rank.
6013 if (SourceBT->getKind() > TargetBT->getKind()) {
6014 // Don't warn about float constants that are precisely
6015 // representable in the target type.
6016 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006017 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006018 // Value might be a float, a float vector, or a float complex.
6019 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006020 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6021 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006022 return;
6023 }
6024
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006025 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006026 return;
6027
John McCallacf0ee52010-10-08 02:01:28 +00006028 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006029 }
6030 return;
6031 }
6032
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006033 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006034 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006035 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006036 return;
6037
Chandler Carruth22c7a792011-02-17 11:05:49 +00006038 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006039 // We also want to warn on, e.g., "int i = -1.234"
6040 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6041 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6042 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6043
Chandler Carruth016ef402011-04-10 08:36:24 +00006044 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6045 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006046 } else {
6047 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6048 }
6049 }
John McCall263a48b2010-01-04 23:31:57 +00006050
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006051 // If the target is bool, warn if expr is a function or method call.
6052 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6053 isa<CallExpr>(E)) {
6054 // Check last argument of function call to see if it is an
6055 // implicit cast from a type matching the type the result
6056 // is being cast to.
6057 CallExpr *CEx = cast<CallExpr>(E);
6058 unsigned NumArgs = CEx->getNumArgs();
6059 if (NumArgs > 0) {
6060 Expr *LastA = CEx->getArg(NumArgs - 1);
6061 Expr *InnerE = LastA->IgnoreParenImpCasts();
6062 const Type *InnerType =
6063 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6064 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6065 // Warn on this floating-point to bool conversion
6066 DiagnoseImpCast(S, E, T, CC,
6067 diag::warn_impcast_floating_point_to_bool);
6068 }
6069 }
6070 }
John McCall263a48b2010-01-04 23:31:57 +00006071 return;
6072 }
6073
Richard Trieubeaf3452011-05-29 19:59:02 +00006074 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006075 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006076 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006077 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006078 SourceLocation Loc = E->getSourceRange().getBegin();
6079 if (Loc.isMacroID())
6080 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006081 if (!Loc.isMacroID() || CC.isMacroID())
6082 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6083 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006084 << FixItHint::CreateReplacement(Loc,
6085 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006086 }
6087
David Blaikie9366d2b2012-06-19 21:19:06 +00006088 if (!Source->isIntegerType() || !Target->isIntegerType())
6089 return;
6090
David Blaikie7555b6a2012-05-15 16:56:36 +00006091 // TODO: remove this early return once the false positives for constant->bool
6092 // in templates, macros, etc, are reduced or removed.
6093 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6094 return;
6095
John McCallcc7e5bf2010-05-06 08:58:33 +00006096 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006097 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006098
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006099 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006100 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006101 // TODO: this should happen for bitfield stores, too.
6102 llvm::APSInt Value(32);
6103 if (E->isIntegerConstantExpr(Value, S.Context)) {
6104 if (S.SourceMgr.isInSystemMacro(CC))
6105 return;
6106
John McCall18a2c2c2010-11-09 22:22:12 +00006107 std::string PrettySourceValue = Value.toString(10);
6108 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006109
Ted Kremenek33ba9952011-10-22 02:37:33 +00006110 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6111 S.PDiag(diag::warn_impcast_integer_precision_constant)
6112 << PrettySourceValue << PrettyTargetValue
6113 << E->getType() << T << E->getSourceRange()
6114 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006115 return;
6116 }
6117
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006118 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6119 if (S.SourceMgr.isInSystemMacro(CC))
6120 return;
6121
David Blaikie9455da02012-04-12 22:40:54 +00006122 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006123 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6124 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006125 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006126 }
6127
6128 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6129 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6130 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006131
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006132 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006133 return;
6134
John McCallcc7e5bf2010-05-06 08:58:33 +00006135 unsigned DiagID = diag::warn_impcast_integer_sign;
6136
6137 // Traditionally, gcc has warned about this under -Wsign-compare.
6138 // We also want to warn about it in -Wconversion.
6139 // So if -Wconversion is off, use a completely identical diagnostic
6140 // in the sign-compare group.
6141 // The conditional-checking code will
6142 if (ICContext) {
6143 DiagID = diag::warn_impcast_integer_sign_conditional;
6144 *ICContext = true;
6145 }
6146
John McCallacf0ee52010-10-08 02:01:28 +00006147 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006148 }
6149
Douglas Gregora78f1932011-02-22 02:45:07 +00006150 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006151 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6152 // type, to give us better diagnostics.
6153 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006154 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6156 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6157 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6158 SourceType = S.Context.getTypeDeclType(Enum);
6159 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6160 }
6161 }
6162
Douglas Gregora78f1932011-02-22 02:45:07 +00006163 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6164 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006165 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6166 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006167 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006168 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006169 return;
6170
Douglas Gregor364f7db2011-03-12 00:14:31 +00006171 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006172 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006173 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006174
John McCall263a48b2010-01-04 23:31:57 +00006175 return;
6176}
6177
David Blaikie18e9ac72012-05-15 21:57:38 +00006178void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6179 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006180
6181void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006182 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006183 E = E->IgnoreParenImpCasts();
6184
6185 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006186 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006187
John McCallacf0ee52010-10-08 02:01:28 +00006188 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006189 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006190 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006191 return;
6192}
6193
David Blaikie18e9ac72012-05-15 21:57:38 +00006194void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6195 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006196 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006197
6198 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006199 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6200 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006201
6202 // If -Wconversion would have warned about either of the candidates
6203 // for a signedness conversion to the context type...
6204 if (!Suspicious) return;
6205
6206 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006207 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006208 return;
6209
John McCallcc7e5bf2010-05-06 08:58:33 +00006210 // ...then check whether it would have warned about either of the
6211 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006212 if (E->getType() == T) return;
6213
6214 Suspicious = false;
6215 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6216 E->getType(), CC, &Suspicious);
6217 if (!Suspicious)
6218 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006219 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006220}
6221
6222/// AnalyzeImplicitConversions - Find and report any interesting
6223/// implicit conversions in the given expression. There are a couple
6224/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006225void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006226 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006227 Expr *E = OrigE->IgnoreParenImpCasts();
6228
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006229 if (E->isTypeDependent() || E->isValueDependent())
6230 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006231
John McCallcc7e5bf2010-05-06 08:58:33 +00006232 // For conditional operators, we analyze the arguments as if they
6233 // were being fed directly into the output.
6234 if (isa<ConditionalOperator>(E)) {
6235 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006236 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006237 return;
6238 }
6239
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006240 // Check implicit argument conversions for function calls.
6241 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6242 CheckImplicitArgumentConversions(S, Call, CC);
6243
John McCallcc7e5bf2010-05-06 08:58:33 +00006244 // Go ahead and check any implicit conversions we might have skipped.
6245 // The non-canonical typecheck is just an optimization;
6246 // CheckImplicitConversion will filter out dead implicit conversions.
6247 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006248 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006249
6250 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006251
6252 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006253 if (POE->getResultExpr())
6254 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006255 }
6256
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006257 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6258 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6259
John McCallcc7e5bf2010-05-06 08:58:33 +00006260 // Skip past explicit casts.
6261 if (isa<ExplicitCastExpr>(E)) {
6262 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006263 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006264 }
6265
John McCalld2a53122010-11-09 23:24:47 +00006266 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6267 // Do a somewhat different check with comparison operators.
6268 if (BO->isComparisonOp())
6269 return AnalyzeComparison(S, BO);
6270
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006271 // And with simple assignments.
6272 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006273 return AnalyzeAssignment(S, BO);
6274 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006275
6276 // These break the otherwise-useful invariant below. Fortunately,
6277 // we don't really need to recurse into them, because any internal
6278 // expressions should have been analyzed already when they were
6279 // built into statements.
6280 if (isa<StmtExpr>(E)) return;
6281
6282 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006283 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006284
6285 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006286 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006287 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006288 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006289 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006290 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006291 if (!ChildExpr)
6292 continue;
6293
Richard Trieu955231d2014-01-25 01:10:35 +00006294 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006295 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006296 // Ignore checking string literals that are in logical and operators.
6297 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006298 continue;
6299 AnalyzeImplicitConversions(S, ChildExpr, CC);
6300 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006301}
6302
6303} // end anonymous namespace
6304
Richard Trieu3bb8b562014-02-26 02:36:06 +00006305enum {
6306 AddressOf,
6307 FunctionPointer,
6308 ArrayPointer
6309};
6310
Richard Trieuc1888e02014-06-28 23:25:37 +00006311// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6312// Returns true when emitting a warning about taking the address of a reference.
6313static bool CheckForReference(Sema &SemaRef, const Expr *E,
6314 PartialDiagnostic PD) {
6315 E = E->IgnoreParenImpCasts();
6316
6317 const FunctionDecl *FD = nullptr;
6318
6319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6320 if (!DRE->getDecl()->getType()->isReferenceType())
6321 return false;
6322 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6323 if (!M->getMemberDecl()->getType()->isReferenceType())
6324 return false;
6325 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6326 if (!Call->getCallReturnType()->isReferenceType())
6327 return false;
6328 FD = Call->getDirectCallee();
6329 } else {
6330 return false;
6331 }
6332
6333 SemaRef.Diag(E->getExprLoc(), PD);
6334
6335 // If possible, point to location of function.
6336 if (FD) {
6337 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6338 }
6339
6340 return true;
6341}
6342
Richard Trieu3bb8b562014-02-26 02:36:06 +00006343/// \brief Diagnose pointers that are always non-null.
6344/// \param E the expression containing the pointer
6345/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6346/// compared to a null pointer
6347/// \param IsEqual True when the comparison is equal to a null pointer
6348/// \param Range Extra SourceRange to highlight in the diagnostic
6349void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6350 Expr::NullPointerConstantKind NullKind,
6351 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006352 if (!E)
6353 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006354
6355 // Don't warn inside macros.
6356 if (E->getExprLoc().isMacroID())
6357 return;
6358 E = E->IgnoreImpCasts();
6359
6360 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6361
Richard Trieuf7432752014-06-06 21:39:26 +00006362 if (isa<CXXThisExpr>(E)) {
6363 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6364 : diag::warn_this_bool_conversion;
6365 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6366 return;
6367 }
6368
Richard Trieu3bb8b562014-02-26 02:36:06 +00006369 bool IsAddressOf = false;
6370
6371 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6372 if (UO->getOpcode() != UO_AddrOf)
6373 return;
6374 IsAddressOf = true;
6375 E = UO->getSubExpr();
6376 }
6377
Richard Trieuc1888e02014-06-28 23:25:37 +00006378 if (IsAddressOf) {
6379 unsigned DiagID = IsCompare
6380 ? diag::warn_address_of_reference_null_compare
6381 : diag::warn_address_of_reference_bool_conversion;
6382 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6383 << IsEqual;
6384 if (CheckForReference(*this, E, PD)) {
6385 return;
6386 }
6387 }
6388
Richard Trieu3bb8b562014-02-26 02:36:06 +00006389 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006390 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006391 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6392 D = R->getDecl();
6393 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6394 D = M->getMemberDecl();
6395 }
6396
6397 // Weak Decls can be null.
6398 if (!D || D->isWeak())
6399 return;
6400
6401 QualType T = D->getType();
6402 const bool IsArray = T->isArrayType();
6403 const bool IsFunction = T->isFunctionType();
6404
Richard Trieuc1888e02014-06-28 23:25:37 +00006405 // Address of function is used to silence the function warning.
6406 if (IsAddressOf && IsFunction) {
6407 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006408 }
6409
6410 // Found nothing.
6411 if (!IsAddressOf && !IsFunction && !IsArray)
6412 return;
6413
6414 // Pretty print the expression for the diagnostic.
6415 std::string Str;
6416 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006417 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006418
6419 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6420 : diag::warn_impcast_pointer_to_bool;
6421 unsigned DiagType;
6422 if (IsAddressOf)
6423 DiagType = AddressOf;
6424 else if (IsFunction)
6425 DiagType = FunctionPointer;
6426 else if (IsArray)
6427 DiagType = ArrayPointer;
6428 else
6429 llvm_unreachable("Could not determine diagnostic.");
6430 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6431 << Range << IsEqual;
6432
6433 if (!IsFunction)
6434 return;
6435
6436 // Suggest '&' to silence the function warning.
6437 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6438 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6439
6440 // Check to see if '()' fixit should be emitted.
6441 QualType ReturnType;
6442 UnresolvedSet<4> NonTemplateOverloads;
6443 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6444 if (ReturnType.isNull())
6445 return;
6446
6447 if (IsCompare) {
6448 // There are two cases here. If there is null constant, the only suggest
6449 // for a pointer return type. If the null is 0, then suggest if the return
6450 // type is a pointer or an integer type.
6451 if (!ReturnType->isPointerType()) {
6452 if (NullKind == Expr::NPCK_ZeroExpression ||
6453 NullKind == Expr::NPCK_ZeroLiteral) {
6454 if (!ReturnType->isIntegerType())
6455 return;
6456 } else {
6457 return;
6458 }
6459 }
6460 } else { // !IsCompare
6461 // For function to bool, only suggest if the function pointer has bool
6462 // return type.
6463 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6464 return;
6465 }
6466 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006467 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006468}
6469
6470
John McCallcc7e5bf2010-05-06 08:58:33 +00006471/// Diagnoses "dangerous" implicit conversions within the given
6472/// expression (which is a full expression). Implements -Wconversion
6473/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006474///
6475/// \param CC the "context" location of the implicit conversion, i.e.
6476/// the most location of the syntactic entity requiring the implicit
6477/// conversion
6478void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006479 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006480 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006481 return;
6482
6483 // Don't diagnose for value- or type-dependent expressions.
6484 if (E->isTypeDependent() || E->isValueDependent())
6485 return;
6486
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006487 // Check for array bounds violations in cases where the check isn't triggered
6488 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6489 // ArraySubscriptExpr is on the RHS of a variable initialization.
6490 CheckArrayAccess(E);
6491
John McCallacf0ee52010-10-08 02:01:28 +00006492 // This is not the right CC for (e.g.) a variable initialization.
6493 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006494}
6495
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006496/// Diagnose when expression is an integer constant expression and its evaluation
6497/// results in integer overflow
6498void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006499 if (isa<BinaryOperator>(E->IgnoreParens()))
6500 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006501}
6502
Richard Smithc406cb72013-01-17 01:17:56 +00006503namespace {
6504/// \brief Visitor for expressions which looks for unsequenced operations on the
6505/// same object.
6506class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006507 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6508
Richard Smithc406cb72013-01-17 01:17:56 +00006509 /// \brief A tree of sequenced regions within an expression. Two regions are
6510 /// unsequenced if one is an ancestor or a descendent of the other. When we
6511 /// finish processing an expression with sequencing, such as a comma
6512 /// expression, we fold its tree nodes into its parent, since they are
6513 /// unsequenced with respect to nodes we will visit later.
6514 class SequenceTree {
6515 struct Value {
6516 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6517 unsigned Parent : 31;
6518 bool Merged : 1;
6519 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006520 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006521
6522 public:
6523 /// \brief A region within an expression which may be sequenced with respect
6524 /// to some other region.
6525 class Seq {
6526 explicit Seq(unsigned N) : Index(N) {}
6527 unsigned Index;
6528 friend class SequenceTree;
6529 public:
6530 Seq() : Index(0) {}
6531 };
6532
6533 SequenceTree() { Values.push_back(Value(0)); }
6534 Seq root() const { return Seq(0); }
6535
6536 /// \brief Create a new sequence of operations, which is an unsequenced
6537 /// subset of \p Parent. This sequence of operations is sequenced with
6538 /// respect to other children of \p Parent.
6539 Seq allocate(Seq Parent) {
6540 Values.push_back(Value(Parent.Index));
6541 return Seq(Values.size() - 1);
6542 }
6543
6544 /// \brief Merge a sequence of operations into its parent.
6545 void merge(Seq S) {
6546 Values[S.Index].Merged = true;
6547 }
6548
6549 /// \brief Determine whether two operations are unsequenced. This operation
6550 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6551 /// should have been merged into its parent as appropriate.
6552 bool isUnsequenced(Seq Cur, Seq Old) {
6553 unsigned C = representative(Cur.Index);
6554 unsigned Target = representative(Old.Index);
6555 while (C >= Target) {
6556 if (C == Target)
6557 return true;
6558 C = Values[C].Parent;
6559 }
6560 return false;
6561 }
6562
6563 private:
6564 /// \brief Pick a representative for a sequence.
6565 unsigned representative(unsigned K) {
6566 if (Values[K].Merged)
6567 // Perform path compression as we go.
6568 return Values[K].Parent = representative(Values[K].Parent);
6569 return K;
6570 }
6571 };
6572
6573 /// An object for which we can track unsequenced uses.
6574 typedef NamedDecl *Object;
6575
6576 /// Different flavors of object usage which we track. We only track the
6577 /// least-sequenced usage of each kind.
6578 enum UsageKind {
6579 /// A read of an object. Multiple unsequenced reads are OK.
6580 UK_Use,
6581 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006582 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006583 UK_ModAsValue,
6584 /// A modification of an object which is not sequenced before the value
6585 /// computation of the expression, such as n++.
6586 UK_ModAsSideEffect,
6587
6588 UK_Count = UK_ModAsSideEffect + 1
6589 };
6590
6591 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006592 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006593 Expr *Use;
6594 SequenceTree::Seq Seq;
6595 };
6596
6597 struct UsageInfo {
6598 UsageInfo() : Diagnosed(false) {}
6599 Usage Uses[UK_Count];
6600 /// Have we issued a diagnostic for this variable already?
6601 bool Diagnosed;
6602 };
6603 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6604
6605 Sema &SemaRef;
6606 /// Sequenced regions within the expression.
6607 SequenceTree Tree;
6608 /// Declaration modifications and references which we have seen.
6609 UsageInfoMap UsageMap;
6610 /// The region we are currently within.
6611 SequenceTree::Seq Region;
6612 /// Filled in with declarations which were modified as a side-effect
6613 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006614 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006615 /// Expressions to check later. We defer checking these to reduce
6616 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006617 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006618
6619 /// RAII object wrapping the visitation of a sequenced subexpression of an
6620 /// expression. At the end of this process, the side-effects of the evaluation
6621 /// become sequenced with respect to the value computation of the result, so
6622 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6623 /// UK_ModAsValue.
6624 struct SequencedSubexpression {
6625 SequencedSubexpression(SequenceChecker &Self)
6626 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6627 Self.ModAsSideEffect = &ModAsSideEffect;
6628 }
6629 ~SequencedSubexpression() {
6630 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6631 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6632 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6633 Self.addUsage(U, ModAsSideEffect[I].first,
6634 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6635 }
6636 Self.ModAsSideEffect = OldModAsSideEffect;
6637 }
6638
6639 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006640 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6641 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006642 };
6643
Richard Smith40238f02013-06-20 22:21:56 +00006644 /// RAII object wrapping the visitation of a subexpression which we might
6645 /// choose to evaluate as a constant. If any subexpression is evaluated and
6646 /// found to be non-constant, this allows us to suppress the evaluation of
6647 /// the outer expression.
6648 class EvaluationTracker {
6649 public:
6650 EvaluationTracker(SequenceChecker &Self)
6651 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6652 Self.EvalTracker = this;
6653 }
6654 ~EvaluationTracker() {
6655 Self.EvalTracker = Prev;
6656 if (Prev)
6657 Prev->EvalOK &= EvalOK;
6658 }
6659
6660 bool evaluate(const Expr *E, bool &Result) {
6661 if (!EvalOK || E->isValueDependent())
6662 return false;
6663 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6664 return EvalOK;
6665 }
6666
6667 private:
6668 SequenceChecker &Self;
6669 EvaluationTracker *Prev;
6670 bool EvalOK;
6671 } *EvalTracker;
6672
Richard Smithc406cb72013-01-17 01:17:56 +00006673 /// \brief Find the object which is produced by the specified expression,
6674 /// if any.
6675 Object getObject(Expr *E, bool Mod) const {
6676 E = E->IgnoreParenCasts();
6677 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6678 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6679 return getObject(UO->getSubExpr(), Mod);
6680 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6681 if (BO->getOpcode() == BO_Comma)
6682 return getObject(BO->getRHS(), Mod);
6683 if (Mod && BO->isAssignmentOp())
6684 return getObject(BO->getLHS(), Mod);
6685 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6686 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6687 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6688 return ME->getMemberDecl();
6689 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6690 // FIXME: If this is a reference, map through to its value.
6691 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006692 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006693 }
6694
6695 /// \brief Note that an object was modified or used by an expression.
6696 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6697 Usage &U = UI.Uses[UK];
6698 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6699 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6700 ModAsSideEffect->push_back(std::make_pair(O, U));
6701 U.Use = Ref;
6702 U.Seq = Region;
6703 }
6704 }
6705 /// \brief Check whether a modification or use conflicts with a prior usage.
6706 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6707 bool IsModMod) {
6708 if (UI.Diagnosed)
6709 return;
6710
6711 const Usage &U = UI.Uses[OtherKind];
6712 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6713 return;
6714
6715 Expr *Mod = U.Use;
6716 Expr *ModOrUse = Ref;
6717 if (OtherKind == UK_Use)
6718 std::swap(Mod, ModOrUse);
6719
6720 SemaRef.Diag(Mod->getExprLoc(),
6721 IsModMod ? diag::warn_unsequenced_mod_mod
6722 : diag::warn_unsequenced_mod_use)
6723 << O << SourceRange(ModOrUse->getExprLoc());
6724 UI.Diagnosed = true;
6725 }
6726
6727 void notePreUse(Object O, Expr *Use) {
6728 UsageInfo &U = UsageMap[O];
6729 // Uses conflict with other modifications.
6730 checkUsage(O, U, Use, UK_ModAsValue, false);
6731 }
6732 void notePostUse(Object O, Expr *Use) {
6733 UsageInfo &U = UsageMap[O];
6734 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6735 addUsage(U, O, Use, UK_Use);
6736 }
6737
6738 void notePreMod(Object O, Expr *Mod) {
6739 UsageInfo &U = UsageMap[O];
6740 // Modifications conflict with other modifications and with uses.
6741 checkUsage(O, U, Mod, UK_ModAsValue, true);
6742 checkUsage(O, U, Mod, UK_Use, false);
6743 }
6744 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6745 UsageInfo &U = UsageMap[O];
6746 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6747 addUsage(U, O, Use, UK);
6748 }
6749
6750public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006751 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006752 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6753 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006754 Visit(E);
6755 }
6756
6757 void VisitStmt(Stmt *S) {
6758 // Skip all statements which aren't expressions for now.
6759 }
6760
6761 void VisitExpr(Expr *E) {
6762 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006763 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006764 }
6765
6766 void VisitCastExpr(CastExpr *E) {
6767 Object O = Object();
6768 if (E->getCastKind() == CK_LValueToRValue)
6769 O = getObject(E->getSubExpr(), false);
6770
6771 if (O)
6772 notePreUse(O, E);
6773 VisitExpr(E);
6774 if (O)
6775 notePostUse(O, E);
6776 }
6777
6778 void VisitBinComma(BinaryOperator *BO) {
6779 // C++11 [expr.comma]p1:
6780 // Every value computation and side effect associated with the left
6781 // expression is sequenced before every value computation and side
6782 // effect associated with the right expression.
6783 SequenceTree::Seq LHS = Tree.allocate(Region);
6784 SequenceTree::Seq RHS = Tree.allocate(Region);
6785 SequenceTree::Seq OldRegion = Region;
6786
6787 {
6788 SequencedSubexpression SeqLHS(*this);
6789 Region = LHS;
6790 Visit(BO->getLHS());
6791 }
6792
6793 Region = RHS;
6794 Visit(BO->getRHS());
6795
6796 Region = OldRegion;
6797
6798 // Forget that LHS and RHS are sequenced. They are both unsequenced
6799 // with respect to other stuff.
6800 Tree.merge(LHS);
6801 Tree.merge(RHS);
6802 }
6803
6804 void VisitBinAssign(BinaryOperator *BO) {
6805 // The modification is sequenced after the value computation of the LHS
6806 // and RHS, so check it before inspecting the operands and update the
6807 // map afterwards.
6808 Object O = getObject(BO->getLHS(), true);
6809 if (!O)
6810 return VisitExpr(BO);
6811
6812 notePreMod(O, BO);
6813
6814 // C++11 [expr.ass]p7:
6815 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6816 // only once.
6817 //
6818 // Therefore, for a compound assignment operator, O is considered used
6819 // everywhere except within the evaluation of E1 itself.
6820 if (isa<CompoundAssignOperator>(BO))
6821 notePreUse(O, BO);
6822
6823 Visit(BO->getLHS());
6824
6825 if (isa<CompoundAssignOperator>(BO))
6826 notePostUse(O, BO);
6827
6828 Visit(BO->getRHS());
6829
Richard Smith83e37bee2013-06-26 23:16:51 +00006830 // C++11 [expr.ass]p1:
6831 // the assignment is sequenced [...] before the value computation of the
6832 // assignment expression.
6833 // C11 6.5.16/3 has no such rule.
6834 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6835 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006836 }
6837 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6838 VisitBinAssign(CAO);
6839 }
6840
6841 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6842 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6843 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6844 Object O = getObject(UO->getSubExpr(), true);
6845 if (!O)
6846 return VisitExpr(UO);
6847
6848 notePreMod(O, UO);
6849 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006850 // C++11 [expr.pre.incr]p1:
6851 // the expression ++x is equivalent to x+=1
6852 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6853 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006854 }
6855
6856 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6857 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6858 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6859 Object O = getObject(UO->getSubExpr(), true);
6860 if (!O)
6861 return VisitExpr(UO);
6862
6863 notePreMod(O, UO);
6864 Visit(UO->getSubExpr());
6865 notePostMod(O, UO, UK_ModAsSideEffect);
6866 }
6867
6868 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6869 void VisitBinLOr(BinaryOperator *BO) {
6870 // The side-effects of the LHS of an '&&' are sequenced before the
6871 // value computation of the RHS, and hence before the value computation
6872 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6873 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006874 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006875 {
6876 SequencedSubexpression Sequenced(*this);
6877 Visit(BO->getLHS());
6878 }
6879
6880 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006881 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006882 if (!Result)
6883 Visit(BO->getRHS());
6884 } else {
6885 // Check for unsequenced operations in the RHS, treating it as an
6886 // entirely separate evaluation.
6887 //
6888 // FIXME: If there are operations in the RHS which are unsequenced
6889 // with respect to operations outside the RHS, and those operations
6890 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006891 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006892 }
Richard Smithc406cb72013-01-17 01:17:56 +00006893 }
6894 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006895 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006896 {
6897 SequencedSubexpression Sequenced(*this);
6898 Visit(BO->getLHS());
6899 }
6900
6901 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006902 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006903 if (Result)
6904 Visit(BO->getRHS());
6905 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006906 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006907 }
Richard Smithc406cb72013-01-17 01:17:56 +00006908 }
6909
6910 // Only visit the condition, unless we can be sure which subexpression will
6911 // be chosen.
6912 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006913 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006914 {
6915 SequencedSubexpression Sequenced(*this);
6916 Visit(CO->getCond());
6917 }
Richard Smithc406cb72013-01-17 01:17:56 +00006918
6919 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006920 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006921 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006922 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006923 WorkList.push_back(CO->getTrueExpr());
6924 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006925 }
Richard Smithc406cb72013-01-17 01:17:56 +00006926 }
6927
Richard Smithe3dbfe02013-06-30 10:40:20 +00006928 void VisitCallExpr(CallExpr *CE) {
6929 // C++11 [intro.execution]p15:
6930 // When calling a function [...], every value computation and side effect
6931 // associated with any argument expression, or with the postfix expression
6932 // designating the called function, is sequenced before execution of every
6933 // expression or statement in the body of the function [and thus before
6934 // the value computation of its result].
6935 SequencedSubexpression Sequenced(*this);
6936 Base::VisitCallExpr(CE);
6937
6938 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6939 }
6940
Richard Smithc406cb72013-01-17 01:17:56 +00006941 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006942 // This is a call, so all subexpressions are sequenced before the result.
6943 SequencedSubexpression Sequenced(*this);
6944
Richard Smithc406cb72013-01-17 01:17:56 +00006945 if (!CCE->isListInitialization())
6946 return VisitExpr(CCE);
6947
6948 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006949 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006950 SequenceTree::Seq Parent = Region;
6951 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6952 E = CCE->arg_end();
6953 I != E; ++I) {
6954 Region = Tree.allocate(Parent);
6955 Elts.push_back(Region);
6956 Visit(*I);
6957 }
6958
6959 // Forget that the initializers are sequenced.
6960 Region = Parent;
6961 for (unsigned I = 0; I < Elts.size(); ++I)
6962 Tree.merge(Elts[I]);
6963 }
6964
6965 void VisitInitListExpr(InitListExpr *ILE) {
6966 if (!SemaRef.getLangOpts().CPlusPlus11)
6967 return VisitExpr(ILE);
6968
6969 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006970 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006971 SequenceTree::Seq Parent = Region;
6972 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6973 Expr *E = ILE->getInit(I);
6974 if (!E) continue;
6975 Region = Tree.allocate(Parent);
6976 Elts.push_back(Region);
6977 Visit(E);
6978 }
6979
6980 // Forget that the initializers are sequenced.
6981 Region = Parent;
6982 for (unsigned I = 0; I < Elts.size(); ++I)
6983 Tree.merge(Elts[I]);
6984 }
6985};
6986}
6987
6988void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006989 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006990 WorkList.push_back(E);
6991 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006992 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006993 SequenceChecker(*this, Item, WorkList);
6994 }
Richard Smithc406cb72013-01-17 01:17:56 +00006995}
6996
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006997void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6998 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006999 CheckImplicitConversions(E, CheckLoc);
7000 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007001 if (!IsConstexpr && !E->isValueDependent())
7002 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007003}
7004
John McCall1f425642010-11-11 03:21:53 +00007005void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7006 FieldDecl *BitField,
7007 Expr *Init) {
7008 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7009}
7010
Mike Stump0c2ec772010-01-21 03:59:47 +00007011/// CheckParmsForFunctionDef - Check that the parameters of the given
7012/// function are appropriate for the definition of a function. This
7013/// takes care of any checks that cannot be performed on the
7014/// declaration itself, e.g., that the types of each of the function
7015/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007016bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7017 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007018 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007019 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007020 for (; P != PEnd; ++P) {
7021 ParmVarDecl *Param = *P;
7022
Mike Stump0c2ec772010-01-21 03:59:47 +00007023 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7024 // function declarator that is part of a function definition of
7025 // that function shall not have incomplete type.
7026 //
7027 // This is also C++ [dcl.fct]p6.
7028 if (!Param->isInvalidDecl() &&
7029 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007030 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007031 Param->setInvalidDecl();
7032 HasInvalidParm = true;
7033 }
7034
7035 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7036 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007037 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007038 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007039 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007040 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007041 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007042
7043 // C99 6.7.5.3p12:
7044 // If the function declarator is not part of a definition of that
7045 // function, parameters may have incomplete type and may use the [*]
7046 // notation in their sequences of declarator specifiers to specify
7047 // variable length array types.
7048 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007049 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007050 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007051 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007052 // information is added for it.
7053 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007054 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007055 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007056 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007057 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007058
7059 // MSVC destroys objects passed by value in the callee. Therefore a
7060 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007061 // object's destructor. However, we don't perform any direct access check
7062 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007063 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7064 .getCXXABI()
7065 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007066 if (!Param->isInvalidDecl()) {
7067 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7068 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7069 if (!ClassDecl->isInvalidDecl() &&
7070 !ClassDecl->hasIrrelevantDestructor() &&
7071 !ClassDecl->isDependentContext()) {
7072 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7073 MarkFunctionReferenced(Param->getLocation(), Destructor);
7074 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7075 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007076 }
7077 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007078 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007079 }
7080
7081 return HasInvalidParm;
7082}
John McCall2b5c1b22010-08-12 21:44:57 +00007083
7084/// CheckCastAlign - Implements -Wcast-align, which warns when a
7085/// pointer cast increases the alignment requirements.
7086void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7087 // This is actually a lot of work to potentially be doing on every
7088 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007089 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007090 return;
7091
7092 // Ignore dependent types.
7093 if (T->isDependentType() || Op->getType()->isDependentType())
7094 return;
7095
7096 // Require that the destination be a pointer type.
7097 const PointerType *DestPtr = T->getAs<PointerType>();
7098 if (!DestPtr) return;
7099
7100 // If the destination has alignment 1, we're done.
7101 QualType DestPointee = DestPtr->getPointeeType();
7102 if (DestPointee->isIncompleteType()) return;
7103 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7104 if (DestAlign.isOne()) return;
7105
7106 // Require that the source be a pointer type.
7107 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7108 if (!SrcPtr) return;
7109 QualType SrcPointee = SrcPtr->getPointeeType();
7110
7111 // Whitelist casts from cv void*. We already implicitly
7112 // whitelisted casts to cv void*, since they have alignment 1.
7113 // Also whitelist casts involving incomplete types, which implicitly
7114 // includes 'void'.
7115 if (SrcPointee->isIncompleteType()) return;
7116
7117 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7118 if (SrcAlign >= DestAlign) return;
7119
7120 Diag(TRange.getBegin(), diag::warn_cast_align)
7121 << Op->getType() << T
7122 << static_cast<unsigned>(SrcAlign.getQuantity())
7123 << static_cast<unsigned>(DestAlign.getQuantity())
7124 << TRange << Op->getSourceRange();
7125}
7126
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007127static const Type* getElementType(const Expr *BaseExpr) {
7128 const Type* EltType = BaseExpr->getType().getTypePtr();
7129 if (EltType->isAnyPointerType())
7130 return EltType->getPointeeType().getTypePtr();
7131 else if (EltType->isArrayType())
7132 return EltType->getBaseElementTypeUnsafe();
7133 return EltType;
7134}
7135
Chandler Carruth28389f02011-08-05 09:10:50 +00007136/// \brief Check whether this array fits the idiom of a size-one tail padded
7137/// array member of a struct.
7138///
7139/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7140/// commonly used to emulate flexible arrays in C89 code.
7141static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7142 const NamedDecl *ND) {
7143 if (Size != 1 || !ND) return false;
7144
7145 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7146 if (!FD) return false;
7147
7148 // Don't consider sizes resulting from macro expansions or template argument
7149 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007150
7151 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007152 while (TInfo) {
7153 TypeLoc TL = TInfo->getTypeLoc();
7154 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007155 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7156 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007157 TInfo = TDL->getTypeSourceInfo();
7158 continue;
7159 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007160 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7161 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007162 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7163 return false;
7164 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007165 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007166 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007167
7168 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007169 if (!RD) return false;
7170 if (RD->isUnion()) return false;
7171 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7172 if (!CRD->isStandardLayout()) return false;
7173 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007174
Benjamin Kramer8c543672011-08-06 03:04:42 +00007175 // See if this is the last field decl in the record.
7176 const Decl *D = FD;
7177 while ((D = D->getNextDeclInContext()))
7178 if (isa<FieldDecl>(D))
7179 return false;
7180 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007181}
7182
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007183void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007184 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007185 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007186 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007187 if (IndexExpr->isValueDependent())
7188 return;
7189
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007190 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007191 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007192 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007193 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007194 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007195 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007196
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007197 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007198 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007199 return;
Richard Smith13f67182011-12-16 19:31:14 +00007200 if (IndexNegated)
7201 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007202
Craig Topperc3ec1492014-05-26 06:22:03 +00007203 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7205 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007206 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007207 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007208
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007209 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007210 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007211 if (!size.isStrictlyPositive())
7212 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007213
7214 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007215 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007216 // Make sure we're comparing apples to apples when comparing index to size
7217 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7218 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007219 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007220 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007221 if (ptrarith_typesize != array_typesize) {
7222 // There's a cast to a different size type involved
7223 uint64_t ratio = array_typesize / ptrarith_typesize;
7224 // TODO: Be smarter about handling cases where array_typesize is not a
7225 // multiple of ptrarith_typesize
7226 if (ptrarith_typesize * ratio == array_typesize)
7227 size *= llvm::APInt(size.getBitWidth(), ratio);
7228 }
7229 }
7230
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007231 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007232 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007233 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007234 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007235
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007236 // For array subscripting the index must be less than size, but for pointer
7237 // arithmetic also allow the index (offset) to be equal to size since
7238 // computing the next address after the end of the array is legal and
7239 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007240 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007241 return;
7242
7243 // Also don't warn for arrays of size 1 which are members of some
7244 // structure. These are often used to approximate flexible arrays in C89
7245 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007246 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007247 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007248
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007249 // Suppress the warning if the subscript expression (as identified by the
7250 // ']' location) and the index expression are both from macro expansions
7251 // within a system header.
7252 if (ASE) {
7253 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7254 ASE->getRBracketLoc());
7255 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7256 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7257 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007258 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007259 return;
7260 }
7261 }
7262
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007263 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007264 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007265 DiagID = diag::warn_array_index_exceeds_bounds;
7266
7267 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7268 PDiag(DiagID) << index.toString(10, true)
7269 << size.toString(10, true)
7270 << (unsigned)size.getLimitedValue(~0U)
7271 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007272 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007273 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007274 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007275 DiagID = diag::warn_ptr_arith_precedes_bounds;
7276 if (index.isNegative()) index = -index;
7277 }
7278
7279 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7280 PDiag(DiagID) << index.toString(10, true)
7281 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007282 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007283
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007284 if (!ND) {
7285 // Try harder to find a NamedDecl to point at in the note.
7286 while (const ArraySubscriptExpr *ASE =
7287 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7288 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7289 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7290 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7291 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7292 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7293 }
7294
Chandler Carruth1af88f12011-02-17 21:10:52 +00007295 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007296 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7297 PDiag(diag::note_array_index_out_of_bounds)
7298 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007299}
7300
Ted Kremenekdf26df72011-03-01 18:41:00 +00007301void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007302 int AllowOnePastEnd = 0;
7303 while (expr) {
7304 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007305 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007306 case Stmt::ArraySubscriptExprClass: {
7307 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007308 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007309 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007310 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007311 }
7312 case Stmt::UnaryOperatorClass: {
7313 // Only unwrap the * and & unary operators
7314 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7315 expr = UO->getSubExpr();
7316 switch (UO->getOpcode()) {
7317 case UO_AddrOf:
7318 AllowOnePastEnd++;
7319 break;
7320 case UO_Deref:
7321 AllowOnePastEnd--;
7322 break;
7323 default:
7324 return;
7325 }
7326 break;
7327 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007328 case Stmt::ConditionalOperatorClass: {
7329 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7330 if (const Expr *lhs = cond->getLHS())
7331 CheckArrayAccess(lhs);
7332 if (const Expr *rhs = cond->getRHS())
7333 CheckArrayAccess(rhs);
7334 return;
7335 }
7336 default:
7337 return;
7338 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007339 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007340}
John McCall31168b02011-06-15 23:02:42 +00007341
7342//===--- CHECK: Objective-C retain cycles ----------------------------------//
7343
7344namespace {
7345 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007346 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007347 VarDecl *Variable;
7348 SourceRange Range;
7349 SourceLocation Loc;
7350 bool Indirect;
7351
7352 void setLocsFrom(Expr *e) {
7353 Loc = e->getExprLoc();
7354 Range = e->getSourceRange();
7355 }
7356 };
7357}
7358
7359/// Consider whether capturing the given variable can possibly lead to
7360/// a retain cycle.
7361static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007362 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007363 // lifetime. In MRR, it's captured strongly if the variable is
7364 // __block and has an appropriate type.
7365 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7366 return false;
7367
7368 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007369 if (ref)
7370 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007371 return true;
7372}
7373
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007374static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007375 while (true) {
7376 e = e->IgnoreParens();
7377 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7378 switch (cast->getCastKind()) {
7379 case CK_BitCast:
7380 case CK_LValueBitCast:
7381 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007382 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007383 e = cast->getSubExpr();
7384 continue;
7385
John McCall31168b02011-06-15 23:02:42 +00007386 default:
7387 return false;
7388 }
7389 }
7390
7391 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7392 ObjCIvarDecl *ivar = ref->getDecl();
7393 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7394 return false;
7395
7396 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007397 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007398 return false;
7399
7400 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7401 owner.Indirect = true;
7402 return true;
7403 }
7404
7405 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7406 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7407 if (!var) return false;
7408 return considerVariable(var, ref, owner);
7409 }
7410
John McCall31168b02011-06-15 23:02:42 +00007411 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7412 if (member->isArrow()) return false;
7413
7414 // Don't count this as an indirect ownership.
7415 e = member->getBase();
7416 continue;
7417 }
7418
John McCallfe96e0b2011-11-06 09:01:30 +00007419 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7420 // Only pay attention to pseudo-objects on property references.
7421 ObjCPropertyRefExpr *pre
7422 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7423 ->IgnoreParens());
7424 if (!pre) return false;
7425 if (pre->isImplicitProperty()) return false;
7426 ObjCPropertyDecl *property = pre->getExplicitProperty();
7427 if (!property->isRetaining() &&
7428 !(property->getPropertyIvarDecl() &&
7429 property->getPropertyIvarDecl()->getType()
7430 .getObjCLifetime() == Qualifiers::OCL_Strong))
7431 return false;
7432
7433 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007434 if (pre->isSuperReceiver()) {
7435 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7436 if (!owner.Variable)
7437 return false;
7438 owner.Loc = pre->getLocation();
7439 owner.Range = pre->getSourceRange();
7440 return true;
7441 }
John McCallfe96e0b2011-11-06 09:01:30 +00007442 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7443 ->getSourceExpr());
7444 continue;
7445 }
7446
John McCall31168b02011-06-15 23:02:42 +00007447 // Array ivars?
7448
7449 return false;
7450 }
7451}
7452
7453namespace {
7454 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7455 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7456 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007457 Context(Context), Variable(variable), Capturer(nullptr),
7458 VarWillBeReased(false) {}
7459 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007460 VarDecl *Variable;
7461 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007462 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007463
7464 void VisitDeclRefExpr(DeclRefExpr *ref) {
7465 if (ref->getDecl() == Variable && !Capturer)
7466 Capturer = ref;
7467 }
7468
John McCall31168b02011-06-15 23:02:42 +00007469 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7470 if (Capturer) return;
7471 Visit(ref->getBase());
7472 if (Capturer && ref->isFreeIvar())
7473 Capturer = ref;
7474 }
7475
7476 void VisitBlockExpr(BlockExpr *block) {
7477 // Look inside nested blocks
7478 if (block->getBlockDecl()->capturesVariable(Variable))
7479 Visit(block->getBlockDecl()->getBody());
7480 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007481
7482 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7483 if (Capturer) return;
7484 if (OVE->getSourceExpr())
7485 Visit(OVE->getSourceExpr());
7486 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007487 void VisitBinaryOperator(BinaryOperator *BinOp) {
7488 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7489 return;
7490 Expr *LHS = BinOp->getLHS();
7491 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7492 if (DRE->getDecl() != Variable)
7493 return;
7494 if (Expr *RHS = BinOp->getRHS()) {
7495 RHS = RHS->IgnoreParenCasts();
7496 llvm::APSInt Value;
7497 VarWillBeReased =
7498 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7499 }
7500 }
7501 }
John McCall31168b02011-06-15 23:02:42 +00007502 };
7503}
7504
7505/// Check whether the given argument is a block which captures a
7506/// variable.
7507static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7508 assert(owner.Variable && owner.Loc.isValid());
7509
7510 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007511
7512 // Look through [^{...} copy] and Block_copy(^{...}).
7513 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7514 Selector Cmd = ME->getSelector();
7515 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7516 e = ME->getInstanceReceiver();
7517 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007518 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007519 e = e->IgnoreParenCasts();
7520 }
7521 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7522 if (CE->getNumArgs() == 1) {
7523 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007524 if (Fn) {
7525 const IdentifierInfo *FnI = Fn->getIdentifier();
7526 if (FnI && FnI->isStr("_Block_copy")) {
7527 e = CE->getArg(0)->IgnoreParenCasts();
7528 }
7529 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007530 }
7531 }
7532
John McCall31168b02011-06-15 23:02:42 +00007533 BlockExpr *block = dyn_cast<BlockExpr>(e);
7534 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007535 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007536
7537 FindCaptureVisitor visitor(S.Context, owner.Variable);
7538 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007539 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007540}
7541
7542static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7543 RetainCycleOwner &owner) {
7544 assert(capturer);
7545 assert(owner.Variable && owner.Loc.isValid());
7546
7547 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7548 << owner.Variable << capturer->getSourceRange();
7549 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7550 << owner.Indirect << owner.Range;
7551}
7552
7553/// Check for a keyword selector that starts with the word 'add' or
7554/// 'set'.
7555static bool isSetterLikeSelector(Selector sel) {
7556 if (sel.isUnarySelector()) return false;
7557
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007558 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007559 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007560 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007561 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007562 else if (str.startswith("add")) {
7563 // Specially whitelist 'addOperationWithBlock:'.
7564 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7565 return false;
7566 str = str.substr(3);
7567 }
John McCall31168b02011-06-15 23:02:42 +00007568 else
7569 return false;
7570
7571 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007572 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007573}
7574
7575/// Check a message send to see if it's likely to cause a retain cycle.
7576void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7577 // Only check instance methods whose selector looks like a setter.
7578 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7579 return;
7580
7581 // Try to find a variable that the receiver is strongly owned by.
7582 RetainCycleOwner owner;
7583 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007584 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007585 return;
7586 } else {
7587 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7588 owner.Variable = getCurMethodDecl()->getSelfDecl();
7589 owner.Loc = msg->getSuperLoc();
7590 owner.Range = msg->getSuperLoc();
7591 }
7592
7593 // Check whether the receiver is captured by any of the arguments.
7594 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7595 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7596 return diagnoseRetainCycle(*this, capturer, owner);
7597}
7598
7599/// Check a property assign to see if it's likely to cause a retain cycle.
7600void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7601 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007602 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007603 return;
7604
7605 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7606 diagnoseRetainCycle(*this, capturer, owner);
7607}
7608
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007609void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7610 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007611 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007612 return;
7613
7614 // Because we don't have an expression for the variable, we have to set the
7615 // location explicitly here.
7616 Owner.Loc = Var->getLocation();
7617 Owner.Range = Var->getSourceRange();
7618
7619 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7620 diagnoseRetainCycle(*this, Capturer, Owner);
7621}
7622
Ted Kremenek9304da92012-12-21 08:04:28 +00007623static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7624 Expr *RHS, bool isProperty) {
7625 // Check if RHS is an Objective-C object literal, which also can get
7626 // immediately zapped in a weak reference. Note that we explicitly
7627 // allow ObjCStringLiterals, since those are designed to never really die.
7628 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007629
Ted Kremenek64873352012-12-21 22:46:35 +00007630 // This enum needs to match with the 'select' in
7631 // warn_objc_arc_literal_assign (off-by-1).
7632 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7633 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7634 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007635
7636 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007637 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007638 << (isProperty ? 0 : 1)
7639 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007640
7641 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007642}
7643
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007644static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7645 Qualifiers::ObjCLifetime LT,
7646 Expr *RHS, bool isProperty) {
7647 // Strip off any implicit cast added to get to the one ARC-specific.
7648 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7649 if (cast->getCastKind() == CK_ARCConsumeObject) {
7650 S.Diag(Loc, diag::warn_arc_retained_assign)
7651 << (LT == Qualifiers::OCL_ExplicitNone)
7652 << (isProperty ? 0 : 1)
7653 << RHS->getSourceRange();
7654 return true;
7655 }
7656 RHS = cast->getSubExpr();
7657 }
7658
7659 if (LT == Qualifiers::OCL_Weak &&
7660 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7661 return true;
7662
7663 return false;
7664}
7665
Ted Kremenekb36234d2012-12-21 08:04:20 +00007666bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7667 QualType LHS, Expr *RHS) {
7668 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7669
7670 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7671 return false;
7672
7673 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7674 return true;
7675
7676 return false;
7677}
7678
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007679void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7680 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007681 QualType LHSType;
7682 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007683 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007684 ObjCPropertyRefExpr *PRE
7685 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7686 if (PRE && !PRE->isImplicitProperty()) {
7687 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7688 if (PD)
7689 LHSType = PD->getType();
7690 }
7691
7692 if (LHSType.isNull())
7693 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007694
7695 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7696
7697 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007698 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007699 getCurFunction()->markSafeWeakUse(LHS);
7700 }
7701
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007702 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7703 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007704
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007705 // FIXME. Check for other life times.
7706 if (LT != Qualifiers::OCL_None)
7707 return;
7708
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007709 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007710 if (PRE->isImplicitProperty())
7711 return;
7712 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7713 if (!PD)
7714 return;
7715
Bill Wendling44426052012-12-20 19:22:21 +00007716 unsigned Attributes = PD->getPropertyAttributes();
7717 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007718 // when 'assign' attribute was not explicitly specified
7719 // by user, ignore it and rely on property type itself
7720 // for lifetime info.
7721 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7722 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7723 LHSType->isObjCRetainableType())
7724 return;
7725
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007726 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007727 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007728 Diag(Loc, diag::warn_arc_retained_property_assign)
7729 << RHS->getSourceRange();
7730 return;
7731 }
7732 RHS = cast->getSubExpr();
7733 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007734 }
Bill Wendling44426052012-12-20 19:22:21 +00007735 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007736 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7737 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007738 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007739 }
7740}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007741
7742//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7743
7744namespace {
7745bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7746 SourceLocation StmtLoc,
7747 const NullStmt *Body) {
7748 // Do not warn if the body is a macro that expands to nothing, e.g:
7749 //
7750 // #define CALL(x)
7751 // if (condition)
7752 // CALL(0);
7753 //
7754 if (Body->hasLeadingEmptyMacro())
7755 return false;
7756
7757 // Get line numbers of statement and body.
7758 bool StmtLineInvalid;
7759 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7760 &StmtLineInvalid);
7761 if (StmtLineInvalid)
7762 return false;
7763
7764 bool BodyLineInvalid;
7765 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7766 &BodyLineInvalid);
7767 if (BodyLineInvalid)
7768 return false;
7769
7770 // Warn if null statement and body are on the same line.
7771 if (StmtLine != BodyLine)
7772 return false;
7773
7774 return true;
7775}
7776} // Unnamed namespace
7777
7778void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7779 const Stmt *Body,
7780 unsigned DiagID) {
7781 // Since this is a syntactic check, don't emit diagnostic for template
7782 // instantiations, this just adds noise.
7783 if (CurrentInstantiationScope)
7784 return;
7785
7786 // The body should be a null statement.
7787 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7788 if (!NBody)
7789 return;
7790
7791 // Do the usual checks.
7792 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7793 return;
7794
7795 Diag(NBody->getSemiLoc(), DiagID);
7796 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7797}
7798
7799void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7800 const Stmt *PossibleBody) {
7801 assert(!CurrentInstantiationScope); // Ensured by caller
7802
7803 SourceLocation StmtLoc;
7804 const Stmt *Body;
7805 unsigned DiagID;
7806 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7807 StmtLoc = FS->getRParenLoc();
7808 Body = FS->getBody();
7809 DiagID = diag::warn_empty_for_body;
7810 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7811 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7812 Body = WS->getBody();
7813 DiagID = diag::warn_empty_while_body;
7814 } else
7815 return; // Neither `for' nor `while'.
7816
7817 // The body should be a null statement.
7818 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7819 if (!NBody)
7820 return;
7821
7822 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007823 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007824 return;
7825
7826 // Do the usual checks.
7827 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7828 return;
7829
7830 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7831 // noise level low, emit diagnostics only if for/while is followed by a
7832 // CompoundStmt, e.g.:
7833 // for (int i = 0; i < n; i++);
7834 // {
7835 // a(i);
7836 // }
7837 // or if for/while is followed by a statement with more indentation
7838 // than for/while itself:
7839 // for (int i = 0; i < n; i++);
7840 // a(i);
7841 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7842 if (!ProbableTypo) {
7843 bool BodyColInvalid;
7844 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7845 PossibleBody->getLocStart(),
7846 &BodyColInvalid);
7847 if (BodyColInvalid)
7848 return;
7849
7850 bool StmtColInvalid;
7851 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7852 S->getLocStart(),
7853 &StmtColInvalid);
7854 if (StmtColInvalid)
7855 return;
7856
7857 if (BodyCol > StmtCol)
7858 ProbableTypo = true;
7859 }
7860
7861 if (ProbableTypo) {
7862 Diag(NBody->getSemiLoc(), DiagID);
7863 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7864 }
7865}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007866
7867//===--- Layout compatibility ----------------------------------------------//
7868
7869namespace {
7870
7871bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7872
7873/// \brief Check if two enumeration types are layout-compatible.
7874bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7875 // C++11 [dcl.enum] p8:
7876 // Two enumeration types are layout-compatible if they have the same
7877 // underlying type.
7878 return ED1->isComplete() && ED2->isComplete() &&
7879 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7880}
7881
7882/// \brief Check if two fields are layout-compatible.
7883bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7884 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7885 return false;
7886
7887 if (Field1->isBitField() != Field2->isBitField())
7888 return false;
7889
7890 if (Field1->isBitField()) {
7891 // Make sure that the bit-fields are the same length.
7892 unsigned Bits1 = Field1->getBitWidthValue(C);
7893 unsigned Bits2 = Field2->getBitWidthValue(C);
7894
7895 if (Bits1 != Bits2)
7896 return false;
7897 }
7898
7899 return true;
7900}
7901
7902/// \brief Check if two standard-layout structs are layout-compatible.
7903/// (C++11 [class.mem] p17)
7904bool isLayoutCompatibleStruct(ASTContext &C,
7905 RecordDecl *RD1,
7906 RecordDecl *RD2) {
7907 // If both records are C++ classes, check that base classes match.
7908 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7909 // If one of records is a CXXRecordDecl we are in C++ mode,
7910 // thus the other one is a CXXRecordDecl, too.
7911 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7912 // Check number of base classes.
7913 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7914 return false;
7915
7916 // Check the base classes.
7917 for (CXXRecordDecl::base_class_const_iterator
7918 Base1 = D1CXX->bases_begin(),
7919 BaseEnd1 = D1CXX->bases_end(),
7920 Base2 = D2CXX->bases_begin();
7921 Base1 != BaseEnd1;
7922 ++Base1, ++Base2) {
7923 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7924 return false;
7925 }
7926 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7927 // If only RD2 is a C++ class, it should have zero base classes.
7928 if (D2CXX->getNumBases() > 0)
7929 return false;
7930 }
7931
7932 // Check the fields.
7933 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7934 Field2End = RD2->field_end(),
7935 Field1 = RD1->field_begin(),
7936 Field1End = RD1->field_end();
7937 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7938 if (!isLayoutCompatible(C, *Field1, *Field2))
7939 return false;
7940 }
7941 if (Field1 != Field1End || Field2 != Field2End)
7942 return false;
7943
7944 return true;
7945}
7946
7947/// \brief Check if two standard-layout unions are layout-compatible.
7948/// (C++11 [class.mem] p18)
7949bool isLayoutCompatibleUnion(ASTContext &C,
7950 RecordDecl *RD1,
7951 RecordDecl *RD2) {
7952 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007953 for (auto *Field2 : RD2->fields())
7954 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007955
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007956 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007957 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7958 I = UnmatchedFields.begin(),
7959 E = UnmatchedFields.end();
7960
7961 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007962 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007963 bool Result = UnmatchedFields.erase(*I);
7964 (void) Result;
7965 assert(Result);
7966 break;
7967 }
7968 }
7969 if (I == E)
7970 return false;
7971 }
7972
7973 return UnmatchedFields.empty();
7974}
7975
7976bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7977 if (RD1->isUnion() != RD2->isUnion())
7978 return false;
7979
7980 if (RD1->isUnion())
7981 return isLayoutCompatibleUnion(C, RD1, RD2);
7982 else
7983 return isLayoutCompatibleStruct(C, RD1, RD2);
7984}
7985
7986/// \brief Check if two types are layout-compatible in C++11 sense.
7987bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7988 if (T1.isNull() || T2.isNull())
7989 return false;
7990
7991 // C++11 [basic.types] p11:
7992 // If two types T1 and T2 are the same type, then T1 and T2 are
7993 // layout-compatible types.
7994 if (C.hasSameType(T1, T2))
7995 return true;
7996
7997 T1 = T1.getCanonicalType().getUnqualifiedType();
7998 T2 = T2.getCanonicalType().getUnqualifiedType();
7999
8000 const Type::TypeClass TC1 = T1->getTypeClass();
8001 const Type::TypeClass TC2 = T2->getTypeClass();
8002
8003 if (TC1 != TC2)
8004 return false;
8005
8006 if (TC1 == Type::Enum) {
8007 return isLayoutCompatible(C,
8008 cast<EnumType>(T1)->getDecl(),
8009 cast<EnumType>(T2)->getDecl());
8010 } else if (TC1 == Type::Record) {
8011 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8012 return false;
8013
8014 return isLayoutCompatible(C,
8015 cast<RecordType>(T1)->getDecl(),
8016 cast<RecordType>(T2)->getDecl());
8017 }
8018
8019 return false;
8020}
8021}
8022
8023//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8024
8025namespace {
8026/// \brief Given a type tag expression find the type tag itself.
8027///
8028/// \param TypeExpr Type tag expression, as it appears in user's code.
8029///
8030/// \param VD Declaration of an identifier that appears in a type tag.
8031///
8032/// \param MagicValue Type tag magic value.
8033bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8034 const ValueDecl **VD, uint64_t *MagicValue) {
8035 while(true) {
8036 if (!TypeExpr)
8037 return false;
8038
8039 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8040
8041 switch (TypeExpr->getStmtClass()) {
8042 case Stmt::UnaryOperatorClass: {
8043 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8044 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8045 TypeExpr = UO->getSubExpr();
8046 continue;
8047 }
8048 return false;
8049 }
8050
8051 case Stmt::DeclRefExprClass: {
8052 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8053 *VD = DRE->getDecl();
8054 return true;
8055 }
8056
8057 case Stmt::IntegerLiteralClass: {
8058 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8059 llvm::APInt MagicValueAPInt = IL->getValue();
8060 if (MagicValueAPInt.getActiveBits() <= 64) {
8061 *MagicValue = MagicValueAPInt.getZExtValue();
8062 return true;
8063 } else
8064 return false;
8065 }
8066
8067 case Stmt::BinaryConditionalOperatorClass:
8068 case Stmt::ConditionalOperatorClass: {
8069 const AbstractConditionalOperator *ACO =
8070 cast<AbstractConditionalOperator>(TypeExpr);
8071 bool Result;
8072 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8073 if (Result)
8074 TypeExpr = ACO->getTrueExpr();
8075 else
8076 TypeExpr = ACO->getFalseExpr();
8077 continue;
8078 }
8079 return false;
8080 }
8081
8082 case Stmt::BinaryOperatorClass: {
8083 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8084 if (BO->getOpcode() == BO_Comma) {
8085 TypeExpr = BO->getRHS();
8086 continue;
8087 }
8088 return false;
8089 }
8090
8091 default:
8092 return false;
8093 }
8094 }
8095}
8096
8097/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8098///
8099/// \param TypeExpr Expression that specifies a type tag.
8100///
8101/// \param MagicValues Registered magic values.
8102///
8103/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8104/// kind.
8105///
8106/// \param TypeInfo Information about the corresponding C type.
8107///
8108/// \returns true if the corresponding C type was found.
8109bool GetMatchingCType(
8110 const IdentifierInfo *ArgumentKind,
8111 const Expr *TypeExpr, const ASTContext &Ctx,
8112 const llvm::DenseMap<Sema::TypeTagMagicValue,
8113 Sema::TypeTagData> *MagicValues,
8114 bool &FoundWrongKind,
8115 Sema::TypeTagData &TypeInfo) {
8116 FoundWrongKind = false;
8117
8118 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008119 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008120
8121 uint64_t MagicValue;
8122
8123 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8124 return false;
8125
8126 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008127 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008128 if (I->getArgumentKind() != ArgumentKind) {
8129 FoundWrongKind = true;
8130 return false;
8131 }
8132 TypeInfo.Type = I->getMatchingCType();
8133 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8134 TypeInfo.MustBeNull = I->getMustBeNull();
8135 return true;
8136 }
8137 return false;
8138 }
8139
8140 if (!MagicValues)
8141 return false;
8142
8143 llvm::DenseMap<Sema::TypeTagMagicValue,
8144 Sema::TypeTagData>::const_iterator I =
8145 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8146 if (I == MagicValues->end())
8147 return false;
8148
8149 TypeInfo = I->second;
8150 return true;
8151}
8152} // unnamed namespace
8153
8154void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8155 uint64_t MagicValue, QualType Type,
8156 bool LayoutCompatible,
8157 bool MustBeNull) {
8158 if (!TypeTagForDatatypeMagicValues)
8159 TypeTagForDatatypeMagicValues.reset(
8160 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8161
8162 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8163 (*TypeTagForDatatypeMagicValues)[Magic] =
8164 TypeTagData(Type, LayoutCompatible, MustBeNull);
8165}
8166
8167namespace {
8168bool IsSameCharType(QualType T1, QualType T2) {
8169 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8170 if (!BT1)
8171 return false;
8172
8173 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8174 if (!BT2)
8175 return false;
8176
8177 BuiltinType::Kind T1Kind = BT1->getKind();
8178 BuiltinType::Kind T2Kind = BT2->getKind();
8179
8180 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8181 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8182 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8183 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8184}
8185} // unnamed namespace
8186
8187void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8188 const Expr * const *ExprArgs) {
8189 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8190 bool IsPointerAttr = Attr->getIsPointer();
8191
8192 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8193 bool FoundWrongKind;
8194 TypeTagData TypeInfo;
8195 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8196 TypeTagForDatatypeMagicValues.get(),
8197 FoundWrongKind, TypeInfo)) {
8198 if (FoundWrongKind)
8199 Diag(TypeTagExpr->getExprLoc(),
8200 diag::warn_type_tag_for_datatype_wrong_kind)
8201 << TypeTagExpr->getSourceRange();
8202 return;
8203 }
8204
8205 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8206 if (IsPointerAttr) {
8207 // Skip implicit cast of pointer to `void *' (as a function argument).
8208 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008209 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008210 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008211 ArgumentExpr = ICE->getSubExpr();
8212 }
8213 QualType ArgumentType = ArgumentExpr->getType();
8214
8215 // Passing a `void*' pointer shouldn't trigger a warning.
8216 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8217 return;
8218
8219 if (TypeInfo.MustBeNull) {
8220 // Type tag with matching void type requires a null pointer.
8221 if (!ArgumentExpr->isNullPointerConstant(Context,
8222 Expr::NPC_ValueDependentIsNotNull)) {
8223 Diag(ArgumentExpr->getExprLoc(),
8224 diag::warn_type_safety_null_pointer_required)
8225 << ArgumentKind->getName()
8226 << ArgumentExpr->getSourceRange()
8227 << TypeTagExpr->getSourceRange();
8228 }
8229 return;
8230 }
8231
8232 QualType RequiredType = TypeInfo.Type;
8233 if (IsPointerAttr)
8234 RequiredType = Context.getPointerType(RequiredType);
8235
8236 bool mismatch = false;
8237 if (!TypeInfo.LayoutCompatible) {
8238 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8239
8240 // C++11 [basic.fundamental] p1:
8241 // Plain char, signed char, and unsigned char are three distinct types.
8242 //
8243 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8244 // char' depending on the current char signedness mode.
8245 if (mismatch)
8246 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8247 RequiredType->getPointeeType())) ||
8248 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8249 mismatch = false;
8250 } else
8251 if (IsPointerAttr)
8252 mismatch = !isLayoutCompatible(Context,
8253 ArgumentType->getPointeeType(),
8254 RequiredType->getPointeeType());
8255 else
8256 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8257
8258 if (mismatch)
8259 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008260 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008261 << TypeInfo.LayoutCompatible << RequiredType
8262 << ArgumentExpr->getSourceRange()
8263 << TypeTagExpr->getSourceRange();
8264}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008265