blob: c1263d45eb40402c4c5c6459be98df09665c9bab [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
Yi Kong26d104a2014-08-13 19:18:14 +0000627 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
628 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
629 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
630 }
631
Tim Northover12670412014-02-19 10:37:05 +0000632 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
633 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000634
Yi Kong4efadfb2014-07-03 16:01:25 +0000635 // For intrinsics which take an immediate value as part of the instruction,
636 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000637 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000638 switch (BuiltinID) {
639 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000640 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
641 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000642 case ARM::BI__builtin_arm_vcvtr_f:
643 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000644 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000645 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000646 case ARM::BI__builtin_arm_isb:
647 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000648 }
Nate Begemand773fe62010-06-13 04:47:52 +0000649
Nate Begemanf568b072010-08-03 21:32:34 +0000650 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000651 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000652}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000653
Tim Northover573cbee2014-05-24 12:52:07 +0000654bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000655 CallExpr *TheCall) {
656 llvm::APSInt Result;
657
Tim Northover573cbee2014-05-24 12:52:07 +0000658 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000659 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
660 BuiltinID == AArch64::BI__builtin_arm_strex ||
661 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000662 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
663 }
664
Yi Konga5548432014-08-13 19:18:20 +0000665 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
666 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
667 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
668 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
669 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
670 }
671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
673 return true;
674
Yi Kong19a29ac2014-07-17 10:52:06 +0000675 // For intrinsics which take an immediate value as part of the instruction,
676 // range check them here.
677 unsigned i = 0, l = 0, u = 0;
678 switch (BuiltinID) {
679 default: return false;
680 case AArch64::BI__builtin_arm_dmb:
681 case AArch64::BI__builtin_arm_dsb:
682 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
683 }
684
Yi Kong19a29ac2014-07-17 10:52:06 +0000685 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000686}
687
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000688bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
689 unsigned i = 0, l = 0, u = 0;
690 switch (BuiltinID) {
691 default: return false;
692 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
693 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000694 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
695 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
696 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
697 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
698 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000699 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000700
Richard Sandiford28940af2014-04-16 08:47:51 +0000701 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000702}
703
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000704bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
705 switch (BuiltinID) {
706 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000707 // This is declared to take (const char*, int)
708 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000709 }
710 return false;
711}
712
Richard Smith55ce3522012-06-25 20:30:08 +0000713/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
714/// parameter with the FormatAttr's correct format_idx and firstDataArg.
715/// Returns true when the format fits the function and the FormatStringInfo has
716/// been populated.
717bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
718 FormatStringInfo *FSI) {
719 FSI->HasVAListArg = Format->getFirstArg() == 0;
720 FSI->FormatIdx = Format->getFormatIdx() - 1;
721 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000722
Richard Smith55ce3522012-06-25 20:30:08 +0000723 // The way the format attribute works in GCC, the implicit this argument
724 // of member functions is counted. However, it doesn't appear in our own
725 // lists, so decrement format_idx in that case.
726 if (IsCXXMember) {
727 if(FSI->FormatIdx == 0)
728 return false;
729 --FSI->FormatIdx;
730 if (FSI->FirstDataArg != 0)
731 --FSI->FirstDataArg;
732 }
733 return true;
734}
Mike Stump11289f42009-09-09 15:08:12 +0000735
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000736/// Checks if a the given expression evaluates to null.
737///
738/// \brief Returns true if the value evaluates to null.
739static bool CheckNonNullExpr(Sema &S,
740 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000741 // As a special case, transparent unions initialized with zero are
742 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000743 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000744 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
745 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000746 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000747 if (const InitListExpr *ILE =
748 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000749 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000750 }
751
752 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000753 return (!Expr->isValueDependent() &&
754 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
755 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000756}
757
758static void CheckNonNullArgument(Sema &S,
759 const Expr *ArgExpr,
760 SourceLocation CallSiteLoc) {
761 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000762 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
763}
764
Ted Kremenek2bc73332014-01-17 06:24:43 +0000765static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000766 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000767 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000768 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000769 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000770 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000771 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000772 if (!NonNull->args_size()) {
773 // Easy case: all pointer arguments are nonnull.
774 for (const auto *Arg : Args)
775 if (S.isValidNonNullAttrType(Arg->getType()))
776 CheckNonNullArgument(S, Arg, CallSiteLoc);
777 return;
778 }
779
780 for (unsigned Val : NonNull->args()) {
781 if (Val >= Args.size())
782 continue;
783 if (NonNullArgs.empty())
784 NonNullArgs.resize(Args.size());
785 NonNullArgs.set(Val);
786 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000787 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000788
789 // Check the attributes on the parameters.
790 ArrayRef<ParmVarDecl*> parms;
791 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
792 parms = FD->parameters();
793 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
794 parms = MD->parameters();
795
Richard Smith588bd9b2014-08-27 04:59:42 +0000796 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000797 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000798 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000799 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000800 if (PVD->hasAttr<NonNullAttr>() ||
801 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
802 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000803 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000804
805 // In case this is a variadic call, check any remaining arguments.
806 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
807 if (NonNullArgs[ArgIndex])
808 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000809}
810
Richard Smith55ce3522012-06-25 20:30:08 +0000811/// Handles the checks for format strings, non-POD arguments to vararg
812/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000813void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
814 unsigned NumParams, bool IsMemberFunction,
815 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000816 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000817 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000818 if (CurContext->isDependentContext())
819 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000820
Ted Kremenekb8176da2010-09-09 04:33:05 +0000821 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000822 llvm::SmallBitVector CheckedVarArgs;
823 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000824 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000825 // Only create vector if there are format attributes.
826 CheckedVarArgs.resize(Args.size());
827
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000828 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000829 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000830 }
Richard Smithd7293d72013-08-05 18:49:43 +0000831 }
Richard Smith55ce3522012-06-25 20:30:08 +0000832
833 // Refuse POD arguments that weren't caught by the format string
834 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000835 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000836 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000837 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000838 if (const Expr *Arg = Args[ArgIdx]) {
839 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
840 checkVariadicArgument(Arg, CallType);
841 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000842 }
Richard Smithd7293d72013-08-05 18:49:43 +0000843 }
Mike Stump11289f42009-09-09 15:08:12 +0000844
Richard Trieu41bc0992013-06-22 00:20:41 +0000845 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000846 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000847
Richard Trieu41bc0992013-06-22 00:20:41 +0000848 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000849 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
850 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000851 }
Richard Smith55ce3522012-06-25 20:30:08 +0000852}
853
854/// CheckConstructorCall - Check a constructor call for correctness and safety
855/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000856void Sema::CheckConstructorCall(FunctionDecl *FDecl,
857 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000858 const FunctionProtoType *Proto,
859 SourceLocation Loc) {
860 VariadicCallType CallType =
861 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000862 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000863 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
864}
865
866/// CheckFunctionCall - Check a direct function call for various correctness
867/// and safety properties not strictly enforced by the C type system.
868bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
869 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000870 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
871 isa<CXXMethodDecl>(FDecl);
872 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
873 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000874 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
875 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000876 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000877 Expr** Args = TheCall->getArgs();
878 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000879 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000880 // If this is a call to a member operator, hide the first argument
881 // from checkCall.
882 // FIXME: Our choice of AST representation here is less than ideal.
883 ++Args;
884 --NumArgs;
885 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000886 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000887 IsMemberFunction, TheCall->getRParenLoc(),
888 TheCall->getCallee()->getSourceRange(), CallType);
889
890 IdentifierInfo *FnInfo = FDecl->getIdentifier();
891 // None of the checks below are needed for functions that don't have
892 // simple names (e.g., C++ conversion functions).
893 if (!FnInfo)
894 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000895
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000896 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
897
Anna Zaks22122702012-01-17 00:37:07 +0000898 unsigned CMId = FDecl->getMemoryFunctionKind();
899 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000900 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000901
Anna Zaks201d4892012-01-13 21:52:01 +0000902 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000903 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000904 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000905 else if (CMId == Builtin::BIstrncat)
906 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000907 else
Anna Zaks22122702012-01-17 00:37:07 +0000908 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000909
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000910 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000911}
912
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000913bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000914 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000915 VariadicCallType CallType =
916 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000917
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000918 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000919 /*IsMemberFunction=*/false,
920 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000921
922 return false;
923}
924
Richard Trieu664c4c62013-06-20 21:03:13 +0000925bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
926 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000927 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
928 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000929 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000931 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000932 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000933 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000934
Richard Trieu664c4c62013-06-20 21:03:13 +0000935 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000936 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000937 CallType = VariadicDoesNotApply;
938 } else if (Ty->isBlockPointerType()) {
939 CallType = VariadicBlock;
940 } else { // Ty->isFunctionPointerType()
941 CallType = VariadicFunction;
942 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000943 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000944
Alp Toker9cacbab2014-01-20 20:26:09 +0000945 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
946 TheCall->getNumArgs()),
947 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000948 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000949
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000950 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000951}
952
Richard Trieu41bc0992013-06-22 00:20:41 +0000953/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
954/// such as function pointers returned from functions.
955bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000956 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000957 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000958 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000959
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 checkCall(/*FDecl=*/nullptr,
961 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
962 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000963 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000964 TheCall->getCallee()->getSourceRange(), CallType);
965
966 return false;
967}
968
Tim Northovere94a34c2014-03-11 10:49:14 +0000969static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
970 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
971 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
972 return false;
973
974 switch (Op) {
975 case AtomicExpr::AO__c11_atomic_init:
976 llvm_unreachable("There is no ordering argument for an init");
977
978 case AtomicExpr::AO__c11_atomic_load:
979 case AtomicExpr::AO__atomic_load_n:
980 case AtomicExpr::AO__atomic_load:
981 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
982 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
983
984 case AtomicExpr::AO__c11_atomic_store:
985 case AtomicExpr::AO__atomic_store:
986 case AtomicExpr::AO__atomic_store_n:
987 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
988 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
989 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
990
991 default:
992 return true;
993 }
994}
995
Richard Smithfeea8832012-04-12 05:08:17 +0000996ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
997 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000998 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
999 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001000
Richard Smithfeea8832012-04-12 05:08:17 +00001001 // All these operations take one of the following forms:
1002 enum {
1003 // C __c11_atomic_init(A *, C)
1004 Init,
1005 // C __c11_atomic_load(A *, int)
1006 Load,
1007 // void __atomic_load(A *, CP, int)
1008 Copy,
1009 // C __c11_atomic_add(A *, M, int)
1010 Arithmetic,
1011 // C __atomic_exchange_n(A *, CP, int)
1012 Xchg,
1013 // void __atomic_exchange(A *, C *, CP, int)
1014 GNUXchg,
1015 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1016 C11CmpXchg,
1017 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1018 GNUCmpXchg
1019 } Form = Init;
1020 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1021 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1022 // where:
1023 // C is an appropriate type,
1024 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1025 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1026 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1027 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001028
Richard Smithfeea8832012-04-12 05:08:17 +00001029 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1030 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1031 && "need to update code for modified C11 atomics");
1032 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1033 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1034 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1035 Op == AtomicExpr::AO__atomic_store_n ||
1036 Op == AtomicExpr::AO__atomic_exchange_n ||
1037 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1038 bool IsAddSub = false;
1039
1040 switch (Op) {
1041 case AtomicExpr::AO__c11_atomic_init:
1042 Form = Init;
1043 break;
1044
1045 case AtomicExpr::AO__c11_atomic_load:
1046 case AtomicExpr::AO__atomic_load_n:
1047 Form = Load;
1048 break;
1049
1050 case AtomicExpr::AO__c11_atomic_store:
1051 case AtomicExpr::AO__atomic_load:
1052 case AtomicExpr::AO__atomic_store:
1053 case AtomicExpr::AO__atomic_store_n:
1054 Form = Copy;
1055 break;
1056
1057 case AtomicExpr::AO__c11_atomic_fetch_add:
1058 case AtomicExpr::AO__c11_atomic_fetch_sub:
1059 case AtomicExpr::AO__atomic_fetch_add:
1060 case AtomicExpr::AO__atomic_fetch_sub:
1061 case AtomicExpr::AO__atomic_add_fetch:
1062 case AtomicExpr::AO__atomic_sub_fetch:
1063 IsAddSub = true;
1064 // Fall through.
1065 case AtomicExpr::AO__c11_atomic_fetch_and:
1066 case AtomicExpr::AO__c11_atomic_fetch_or:
1067 case AtomicExpr::AO__c11_atomic_fetch_xor:
1068 case AtomicExpr::AO__atomic_fetch_and:
1069 case AtomicExpr::AO__atomic_fetch_or:
1070 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001071 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001072 case AtomicExpr::AO__atomic_and_fetch:
1073 case AtomicExpr::AO__atomic_or_fetch:
1074 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001075 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001076 Form = Arithmetic;
1077 break;
1078
1079 case AtomicExpr::AO__c11_atomic_exchange:
1080 case AtomicExpr::AO__atomic_exchange_n:
1081 Form = Xchg;
1082 break;
1083
1084 case AtomicExpr::AO__atomic_exchange:
1085 Form = GNUXchg;
1086 break;
1087
1088 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1089 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1090 Form = C11CmpXchg;
1091 break;
1092
1093 case AtomicExpr::AO__atomic_compare_exchange:
1094 case AtomicExpr::AO__atomic_compare_exchange_n:
1095 Form = GNUCmpXchg;
1096 break;
1097 }
1098
1099 // Check we have the right number of arguments.
1100 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001101 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001102 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001103 << TheCall->getCallee()->getSourceRange();
1104 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001105 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1106 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001107 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001108 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001109 << TheCall->getCallee()->getSourceRange();
1110 return ExprError();
1111 }
1112
Richard Smithfeea8832012-04-12 05:08:17 +00001113 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001114 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001115 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1116 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1117 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001118 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001119 << Ptr->getType() << Ptr->getSourceRange();
1120 return ExprError();
1121 }
1122
Richard Smithfeea8832012-04-12 05:08:17 +00001123 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1124 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1125 QualType ValType = AtomTy; // 'C'
1126 if (IsC11) {
1127 if (!AtomTy->isAtomicType()) {
1128 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1129 << Ptr->getType() << Ptr->getSourceRange();
1130 return ExprError();
1131 }
Richard Smithe00921a2012-09-15 06:09:58 +00001132 if (AtomTy.isConstQualified()) {
1133 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1134 << Ptr->getType() << Ptr->getSourceRange();
1135 return ExprError();
1136 }
Richard Smithfeea8832012-04-12 05:08:17 +00001137 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001138 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001139
Richard Smithfeea8832012-04-12 05:08:17 +00001140 // For an arithmetic operation, the implied arithmetic must be well-formed.
1141 if (Form == Arithmetic) {
1142 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1143 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1144 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1145 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1146 return ExprError();
1147 }
1148 if (!IsAddSub && !ValType->isIntegerType()) {
1149 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1150 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1151 return ExprError();
1152 }
1153 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1154 // For __atomic_*_n operations, the value type must be a scalar integral or
1155 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001156 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001157 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1158 return ExprError();
1159 }
1160
Eli Friedmanaa769812013-09-11 03:49:34 +00001161 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1162 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001163 // For GNU atomics, require a trivially-copyable type. This is not part of
1164 // the GNU atomics specification, but we enforce it for sanity.
1165 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001166 << Ptr->getType() << Ptr->getSourceRange();
1167 return ExprError();
1168 }
1169
Richard Smithfeea8832012-04-12 05:08:17 +00001170 // FIXME: For any builtin other than a load, the ValType must not be
1171 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001172
1173 switch (ValType.getObjCLifetime()) {
1174 case Qualifiers::OCL_None:
1175 case Qualifiers::OCL_ExplicitNone:
1176 // okay
1177 break;
1178
1179 case Qualifiers::OCL_Weak:
1180 case Qualifiers::OCL_Strong:
1181 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001182 // FIXME: Can this happen? By this point, ValType should be known
1183 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001184 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1185 << ValType << Ptr->getSourceRange();
1186 return ExprError();
1187 }
1188
1189 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001190 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001191 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001192 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001193 ResultType = Context.BoolTy;
1194
Richard Smithfeea8832012-04-12 05:08:17 +00001195 // The type of a parameter passed 'by value'. In the GNU atomics, such
1196 // arguments are actually passed as pointers.
1197 QualType ByValType = ValType; // 'CP'
1198 if (!IsC11 && !IsN)
1199 ByValType = Ptr->getType();
1200
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001201 // The first argument --- the pointer --- has a fixed type; we
1202 // deduce the types of the rest of the arguments accordingly. Walk
1203 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001204 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001205 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001206 if (i < NumVals[Form] + 1) {
1207 switch (i) {
1208 case 1:
1209 // The second argument is the non-atomic operand. For arithmetic, this
1210 // is always passed by value, and for a compare_exchange it is always
1211 // passed by address. For the rest, GNU uses by-address and C11 uses
1212 // by-value.
1213 assert(Form != Load);
1214 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1215 Ty = ValType;
1216 else if (Form == Copy || Form == Xchg)
1217 Ty = ByValType;
1218 else if (Form == Arithmetic)
1219 Ty = Context.getPointerDiffType();
1220 else
1221 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1222 break;
1223 case 2:
1224 // The third argument to compare_exchange / GNU exchange is a
1225 // (pointer to a) desired value.
1226 Ty = ByValType;
1227 break;
1228 case 3:
1229 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1230 Ty = Context.BoolTy;
1231 break;
1232 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001233 } else {
1234 // The order(s) are always converted to int.
1235 Ty = Context.IntTy;
1236 }
Richard Smithfeea8832012-04-12 05:08:17 +00001237
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001238 InitializedEntity Entity =
1239 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001240 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1242 if (Arg.isInvalid())
1243 return true;
1244 TheCall->setArg(i, Arg.get());
1245 }
1246
Richard Smithfeea8832012-04-12 05:08:17 +00001247 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001248 SmallVector<Expr*, 5> SubExprs;
1249 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001250 switch (Form) {
1251 case Init:
1252 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001253 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001254 break;
1255 case Load:
1256 SubExprs.push_back(TheCall->getArg(1)); // Order
1257 break;
1258 case Copy:
1259 case Arithmetic:
1260 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001261 SubExprs.push_back(TheCall->getArg(2)); // Order
1262 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001263 break;
1264 case GNUXchg:
1265 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1266 SubExprs.push_back(TheCall->getArg(3)); // Order
1267 SubExprs.push_back(TheCall->getArg(1)); // Val1
1268 SubExprs.push_back(TheCall->getArg(2)); // Val2
1269 break;
1270 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001271 SubExprs.push_back(TheCall->getArg(3)); // Order
1272 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001273 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001274 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001275 break;
1276 case GNUCmpXchg:
1277 SubExprs.push_back(TheCall->getArg(4)); // Order
1278 SubExprs.push_back(TheCall->getArg(1)); // Val1
1279 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1280 SubExprs.push_back(TheCall->getArg(2)); // Val2
1281 SubExprs.push_back(TheCall->getArg(3)); // Weak
1282 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001283 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001284
1285 if (SubExprs.size() >= 2 && Form != Init) {
1286 llvm::APSInt Result(32);
1287 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1288 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001289 Diag(SubExprs[1]->getLocStart(),
1290 diag::warn_atomic_op_has_invalid_memory_order)
1291 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001292 }
1293
Fariborz Jahanian615de762013-05-28 17:37:39 +00001294 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1295 SubExprs, ResultType, Op,
1296 TheCall->getRParenLoc());
1297
1298 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1299 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1300 Context.AtomicUsesUnsupportedLibcall(AE))
1301 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1302 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001303
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001304 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001305}
1306
1307
John McCall29ad95b2011-08-27 01:09:30 +00001308/// checkBuiltinArgument - Given a call to a builtin function, perform
1309/// normal type-checking on the given argument, updating the call in
1310/// place. This is useful when a builtin function requires custom
1311/// type-checking for some of its arguments but not necessarily all of
1312/// them.
1313///
1314/// Returns true on error.
1315static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1316 FunctionDecl *Fn = E->getDirectCallee();
1317 assert(Fn && "builtin call without direct callee!");
1318
1319 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1320 InitializedEntity Entity =
1321 InitializedEntity::InitializeParameter(S.Context, Param);
1322
1323 ExprResult Arg = E->getArg(0);
1324 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1325 if (Arg.isInvalid())
1326 return true;
1327
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001328 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001329 return false;
1330}
1331
Chris Lattnerdc046542009-05-08 06:58:22 +00001332/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1333/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1334/// type of its first argument. The main ActOnCallExpr routines have already
1335/// promoted the types of arguments because all of these calls are prototyped as
1336/// void(...).
1337///
1338/// This function goes through and does final semantic checking for these
1339/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001340ExprResult
1341Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001342 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001343 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1344 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1345
1346 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001347 if (TheCall->getNumArgs() < 1) {
1348 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1349 << 0 << 1 << TheCall->getNumArgs()
1350 << TheCall->getCallee()->getSourceRange();
1351 return ExprError();
1352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerdc046542009-05-08 06:58:22 +00001354 // Inspect the first argument of the atomic builtin. This should always be
1355 // a pointer type, whose element is an integral scalar or pointer type.
1356 // Because it is a pointer type, we don't have to worry about any implicit
1357 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001358 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001359 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001360 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1361 if (FirstArgResult.isInvalid())
1362 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001363 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001364 TheCall->setArg(0, FirstArg);
1365
John McCall31168b02011-06-15 23:02:42 +00001366 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1367 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001368 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1369 << FirstArg->getType() << FirstArg->getSourceRange();
1370 return ExprError();
1371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
John McCall31168b02011-06-15 23:02:42 +00001373 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001374 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001375 !ValType->isBlockPointerType()) {
1376 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1377 << FirstArg->getType() << FirstArg->getSourceRange();
1378 return ExprError();
1379 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001380
John McCall31168b02011-06-15 23:02:42 +00001381 switch (ValType.getObjCLifetime()) {
1382 case Qualifiers::OCL_None:
1383 case Qualifiers::OCL_ExplicitNone:
1384 // okay
1385 break;
1386
1387 case Qualifiers::OCL_Weak:
1388 case Qualifiers::OCL_Strong:
1389 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001390 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001391 << ValType << FirstArg->getSourceRange();
1392 return ExprError();
1393 }
1394
John McCallb50451a2011-10-05 07:41:44 +00001395 // Strip any qualifiers off ValType.
1396 ValType = ValType.getUnqualifiedType();
1397
Chandler Carruth3973af72010-07-18 20:54:12 +00001398 // The majority of builtins return a value, but a few have special return
1399 // types, so allow them to override appropriately below.
1400 QualType ResultType = ValType;
1401
Chris Lattnerdc046542009-05-08 06:58:22 +00001402 // We need to figure out which concrete builtin this maps onto. For example,
1403 // __sync_fetch_and_add with a 2 byte object turns into
1404 // __sync_fetch_and_add_2.
1405#define BUILTIN_ROW(x) \
1406 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1407 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Chris Lattnerdc046542009-05-08 06:58:22 +00001409 static const unsigned BuiltinIndices[][5] = {
1410 BUILTIN_ROW(__sync_fetch_and_add),
1411 BUILTIN_ROW(__sync_fetch_and_sub),
1412 BUILTIN_ROW(__sync_fetch_and_or),
1413 BUILTIN_ROW(__sync_fetch_and_and),
1414 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattnerdc046542009-05-08 06:58:22 +00001416 BUILTIN_ROW(__sync_add_and_fetch),
1417 BUILTIN_ROW(__sync_sub_and_fetch),
1418 BUILTIN_ROW(__sync_and_and_fetch),
1419 BUILTIN_ROW(__sync_or_and_fetch),
1420 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001421
Chris Lattnerdc046542009-05-08 06:58:22 +00001422 BUILTIN_ROW(__sync_val_compare_and_swap),
1423 BUILTIN_ROW(__sync_bool_compare_and_swap),
1424 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001425 BUILTIN_ROW(__sync_lock_release),
1426 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001427 };
Mike Stump11289f42009-09-09 15:08:12 +00001428#undef BUILTIN_ROW
1429
Chris Lattnerdc046542009-05-08 06:58:22 +00001430 // Determine the index of the size.
1431 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001432 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001433 case 1: SizeIndex = 0; break;
1434 case 2: SizeIndex = 1; break;
1435 case 4: SizeIndex = 2; break;
1436 case 8: SizeIndex = 3; break;
1437 case 16: SizeIndex = 4; break;
1438 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001439 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1440 << FirstArg->getType() << FirstArg->getSourceRange();
1441 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
Chris Lattnerdc046542009-05-08 06:58:22 +00001444 // Each of these builtins has one pointer argument, followed by some number of
1445 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1446 // that we ignore. Find out which row of BuiltinIndices to read from as well
1447 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001448 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001449 unsigned BuiltinIndex, NumFixed = 1;
1450 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001451 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001452 case Builtin::BI__sync_fetch_and_add:
1453 case Builtin::BI__sync_fetch_and_add_1:
1454 case Builtin::BI__sync_fetch_and_add_2:
1455 case Builtin::BI__sync_fetch_and_add_4:
1456 case Builtin::BI__sync_fetch_and_add_8:
1457 case Builtin::BI__sync_fetch_and_add_16:
1458 BuiltinIndex = 0;
1459 break;
1460
1461 case Builtin::BI__sync_fetch_and_sub:
1462 case Builtin::BI__sync_fetch_and_sub_1:
1463 case Builtin::BI__sync_fetch_and_sub_2:
1464 case Builtin::BI__sync_fetch_and_sub_4:
1465 case Builtin::BI__sync_fetch_and_sub_8:
1466 case Builtin::BI__sync_fetch_and_sub_16:
1467 BuiltinIndex = 1;
1468 break;
1469
1470 case Builtin::BI__sync_fetch_and_or:
1471 case Builtin::BI__sync_fetch_and_or_1:
1472 case Builtin::BI__sync_fetch_and_or_2:
1473 case Builtin::BI__sync_fetch_and_or_4:
1474 case Builtin::BI__sync_fetch_and_or_8:
1475 case Builtin::BI__sync_fetch_and_or_16:
1476 BuiltinIndex = 2;
1477 break;
1478
1479 case Builtin::BI__sync_fetch_and_and:
1480 case Builtin::BI__sync_fetch_and_and_1:
1481 case Builtin::BI__sync_fetch_and_and_2:
1482 case Builtin::BI__sync_fetch_and_and_4:
1483 case Builtin::BI__sync_fetch_and_and_8:
1484 case Builtin::BI__sync_fetch_and_and_16:
1485 BuiltinIndex = 3;
1486 break;
Mike Stump11289f42009-09-09 15:08:12 +00001487
Douglas Gregor73722482011-11-28 16:30:08 +00001488 case Builtin::BI__sync_fetch_and_xor:
1489 case Builtin::BI__sync_fetch_and_xor_1:
1490 case Builtin::BI__sync_fetch_and_xor_2:
1491 case Builtin::BI__sync_fetch_and_xor_4:
1492 case Builtin::BI__sync_fetch_and_xor_8:
1493 case Builtin::BI__sync_fetch_and_xor_16:
1494 BuiltinIndex = 4;
1495 break;
1496
1497 case Builtin::BI__sync_add_and_fetch:
1498 case Builtin::BI__sync_add_and_fetch_1:
1499 case Builtin::BI__sync_add_and_fetch_2:
1500 case Builtin::BI__sync_add_and_fetch_4:
1501 case Builtin::BI__sync_add_and_fetch_8:
1502 case Builtin::BI__sync_add_and_fetch_16:
1503 BuiltinIndex = 5;
1504 break;
1505
1506 case Builtin::BI__sync_sub_and_fetch:
1507 case Builtin::BI__sync_sub_and_fetch_1:
1508 case Builtin::BI__sync_sub_and_fetch_2:
1509 case Builtin::BI__sync_sub_and_fetch_4:
1510 case Builtin::BI__sync_sub_and_fetch_8:
1511 case Builtin::BI__sync_sub_and_fetch_16:
1512 BuiltinIndex = 6;
1513 break;
1514
1515 case Builtin::BI__sync_and_and_fetch:
1516 case Builtin::BI__sync_and_and_fetch_1:
1517 case Builtin::BI__sync_and_and_fetch_2:
1518 case Builtin::BI__sync_and_and_fetch_4:
1519 case Builtin::BI__sync_and_and_fetch_8:
1520 case Builtin::BI__sync_and_and_fetch_16:
1521 BuiltinIndex = 7;
1522 break;
1523
1524 case Builtin::BI__sync_or_and_fetch:
1525 case Builtin::BI__sync_or_and_fetch_1:
1526 case Builtin::BI__sync_or_and_fetch_2:
1527 case Builtin::BI__sync_or_and_fetch_4:
1528 case Builtin::BI__sync_or_and_fetch_8:
1529 case Builtin::BI__sync_or_and_fetch_16:
1530 BuiltinIndex = 8;
1531 break;
1532
1533 case Builtin::BI__sync_xor_and_fetch:
1534 case Builtin::BI__sync_xor_and_fetch_1:
1535 case Builtin::BI__sync_xor_and_fetch_2:
1536 case Builtin::BI__sync_xor_and_fetch_4:
1537 case Builtin::BI__sync_xor_and_fetch_8:
1538 case Builtin::BI__sync_xor_and_fetch_16:
1539 BuiltinIndex = 9;
1540 break;
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattnerdc046542009-05-08 06:58:22 +00001542 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001543 case Builtin::BI__sync_val_compare_and_swap_1:
1544 case Builtin::BI__sync_val_compare_and_swap_2:
1545 case Builtin::BI__sync_val_compare_and_swap_4:
1546 case Builtin::BI__sync_val_compare_and_swap_8:
1547 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001548 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001549 NumFixed = 2;
1550 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001551
Chris Lattnerdc046542009-05-08 06:58:22 +00001552 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001553 case Builtin::BI__sync_bool_compare_and_swap_1:
1554 case Builtin::BI__sync_bool_compare_and_swap_2:
1555 case Builtin::BI__sync_bool_compare_and_swap_4:
1556 case Builtin::BI__sync_bool_compare_and_swap_8:
1557 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001558 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001559 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001560 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001561 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001562
1563 case Builtin::BI__sync_lock_test_and_set:
1564 case Builtin::BI__sync_lock_test_and_set_1:
1565 case Builtin::BI__sync_lock_test_and_set_2:
1566 case Builtin::BI__sync_lock_test_and_set_4:
1567 case Builtin::BI__sync_lock_test_and_set_8:
1568 case Builtin::BI__sync_lock_test_and_set_16:
1569 BuiltinIndex = 12;
1570 break;
1571
Chris Lattnerdc046542009-05-08 06:58:22 +00001572 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001573 case Builtin::BI__sync_lock_release_1:
1574 case Builtin::BI__sync_lock_release_2:
1575 case Builtin::BI__sync_lock_release_4:
1576 case Builtin::BI__sync_lock_release_8:
1577 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001578 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001579 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001580 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001581 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001582
1583 case Builtin::BI__sync_swap:
1584 case Builtin::BI__sync_swap_1:
1585 case Builtin::BI__sync_swap_2:
1586 case Builtin::BI__sync_swap_4:
1587 case Builtin::BI__sync_swap_8:
1588 case Builtin::BI__sync_swap_16:
1589 BuiltinIndex = 14;
1590 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Chris Lattnerdc046542009-05-08 06:58:22 +00001593 // Now that we know how many fixed arguments we expect, first check that we
1594 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001595 if (TheCall->getNumArgs() < 1+NumFixed) {
1596 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1597 << 0 << 1+NumFixed << TheCall->getNumArgs()
1598 << TheCall->getCallee()->getSourceRange();
1599 return ExprError();
1600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Chris Lattner5b9241b2009-05-08 15:36:58 +00001602 // Get the decl for the concrete builtin from this, we can tell what the
1603 // concrete integer type we should convert to is.
1604 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1605 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001606 FunctionDecl *NewBuiltinDecl;
1607 if (NewBuiltinID == BuiltinID)
1608 NewBuiltinDecl = FDecl;
1609 else {
1610 // Perform builtin lookup to avoid redeclaring it.
1611 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1612 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1613 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1614 assert(Res.getFoundDecl());
1615 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001616 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001617 return ExprError();
1618 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001619
John McCallcf142162010-08-07 06:22:56 +00001620 // The first argument --- the pointer --- has a fixed type; we
1621 // deduce the types of the rest of the arguments accordingly. Walk
1622 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001623 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001624 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattnerdc046542009-05-08 06:58:22 +00001626 // GCC does an implicit conversion to the pointer or integer ValType. This
1627 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001628 // Initialize the argument.
1629 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1630 ValType, /*consume*/ false);
1631 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001632 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001633 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattnerdc046542009-05-08 06:58:22 +00001635 // Okay, we have something that *can* be converted to the right type. Check
1636 // to see if there is a potentially weird extension going on here. This can
1637 // happen when you do an atomic operation on something like an char* and
1638 // pass in 42. The 42 gets converted to char. This is even more strange
1639 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001640 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001641 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001642 }
Mike Stump11289f42009-09-09 15:08:12 +00001643
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001644 ASTContext& Context = this->getASTContext();
1645
1646 // Create a new DeclRefExpr to refer to the new decl.
1647 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1648 Context,
1649 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001650 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001651 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001652 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001653 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001654 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001655 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattnerdc046542009-05-08 06:58:22 +00001657 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001658 // FIXME: This loses syntactic information.
1659 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1660 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1661 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001662 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001663
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001664 // Change the result type of the call to match the original value type. This
1665 // is arbitrary, but the codegen for these builtins ins design to handle it
1666 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001667 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001668
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001669 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001670}
1671
Chris Lattner6436fb62009-02-18 06:01:06 +00001672/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001673/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001674/// Note: It might also make sense to do the UTF-16 conversion here (would
1675/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001676bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001677 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001678 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1679
Douglas Gregorfb65e592011-07-27 05:40:30 +00001680 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001681 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1682 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001683 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001686 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001687 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001688 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001689 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001690 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001691 UTF16 *ToPtr = &ToBuf[0];
1692
1693 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1694 &ToPtr, ToPtr + NumBytes,
1695 strictConversion);
1696 // Check for conversion failure.
1697 if (Result != conversionOK)
1698 Diag(Arg->getLocStart(),
1699 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1700 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001701 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001702}
1703
Chris Lattnere202e6a2007-12-20 00:05:45 +00001704/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1705/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001706bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1707 Expr *Fn = TheCall->getCallee();
1708 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001709 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001710 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1712 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001713 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001714 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001715 return true;
1716 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001717
1718 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001719 return Diag(TheCall->getLocEnd(),
1720 diag::err_typecheck_call_too_few_args_at_least)
1721 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001722 }
1723
John McCall29ad95b2011-08-27 01:09:30 +00001724 // Type-check the first argument normally.
1725 if (checkBuiltinArgument(*this, TheCall, 0))
1726 return true;
1727
Chris Lattnere202e6a2007-12-20 00:05:45 +00001728 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001729 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001730 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001731 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001732 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001733 else if (FunctionDecl *FD = getCurFunctionDecl())
1734 isVariadic = FD->isVariadic();
1735 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001736 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001737
Chris Lattnere202e6a2007-12-20 00:05:45 +00001738 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001739 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1740 return true;
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattner43be2e62007-12-19 23:59:04 +00001743 // Verify that the second argument to the builtin is the last argument of the
1744 // current function or method.
1745 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001746 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001747
Nico Weber9eea7642013-05-24 23:31:57 +00001748 // These are valid if SecondArgIsLastNamedArgument is false after the next
1749 // block.
1750 QualType Type;
1751 SourceLocation ParamLoc;
1752
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001753 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1754 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001755 // FIXME: This isn't correct for methods (results in bogus warning).
1756 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001757 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001758 if (CurBlock)
1759 LastArg = *(CurBlock->TheDecl->param_end()-1);
1760 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001761 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001762 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001763 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001764 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001765
1766 Type = PV->getType();
1767 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001768 }
1769 }
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattner43be2e62007-12-19 23:59:04 +00001771 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001772 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001773 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001774 else if (Type->isReferenceType()) {
1775 Diag(Arg->getLocStart(),
1776 diag::warn_va_start_of_reference_type_is_undefined);
1777 Diag(ParamLoc, diag::note_parameter_type) << Type;
1778 }
1779
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001780 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001781 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001782}
Chris Lattner43be2e62007-12-19 23:59:04 +00001783
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001784bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1785 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1786 // const char *named_addr);
1787
1788 Expr *Func = Call->getCallee();
1789
1790 if (Call->getNumArgs() < 3)
1791 return Diag(Call->getLocEnd(),
1792 diag::err_typecheck_call_too_few_args_at_least)
1793 << 0 /*function call*/ << 3 << Call->getNumArgs();
1794
1795 // Determine whether the current function is variadic or not.
1796 bool IsVariadic;
1797 if (BlockScopeInfo *CurBlock = getCurBlock())
1798 IsVariadic = CurBlock->TheDecl->isVariadic();
1799 else if (FunctionDecl *FD = getCurFunctionDecl())
1800 IsVariadic = FD->isVariadic();
1801 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1802 IsVariadic = MD->isVariadic();
1803 else
1804 llvm_unreachable("unexpected statement type");
1805
1806 if (!IsVariadic) {
1807 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1808 return true;
1809 }
1810
1811 // Type-check the first argument normally.
1812 if (checkBuiltinArgument(*this, Call, 0))
1813 return true;
1814
1815 static const struct {
1816 unsigned ArgNo;
1817 QualType Type;
1818 } ArgumentTypes[] = {
1819 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1820 { 2, Context.getSizeType() },
1821 };
1822
1823 for (const auto &AT : ArgumentTypes) {
1824 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1825 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1826 continue;
1827 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1828 << Arg->getType() << AT.Type << 1 /* different class */
1829 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1830 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1831 }
1832
1833 return false;
1834}
1835
Chris Lattner2da14fb2007-12-20 00:26:33 +00001836/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1837/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001838bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1839 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001840 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001841 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001842 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001843 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001844 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001845 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001846 << SourceRange(TheCall->getArg(2)->getLocStart(),
1847 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001848
John Wiegley01296292011-04-08 18:41:53 +00001849 ExprResult OrigArg0 = TheCall->getArg(0);
1850 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001851
Chris Lattner2da14fb2007-12-20 00:26:33 +00001852 // Do standard promotions between the two arguments, returning their common
1853 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001854 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001855 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1856 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001857
1858 // Make sure any conversions are pushed back into the call; this is
1859 // type safe since unordered compare builtins are declared as "_Bool
1860 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001861 TheCall->setArg(0, OrigArg0.get());
1862 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001863
John Wiegley01296292011-04-08 18:41:53 +00001864 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001865 return false;
1866
Chris Lattner2da14fb2007-12-20 00:26:33 +00001867 // If the common type isn't a real floating type, then the arguments were
1868 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001869 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001870 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001871 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001872 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1873 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner2da14fb2007-12-20 00:26:33 +00001875 return false;
1876}
1877
Benjamin Kramer634fc102010-02-15 22:42:31 +00001878/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1879/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001880/// to check everything. We expect the last argument to be a floating point
1881/// value.
1882bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1883 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001884 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001885 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001886 if (TheCall->getNumArgs() > NumArgs)
1887 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001888 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001889 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001890 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001891 (*(TheCall->arg_end()-1))->getLocEnd());
1892
Benjamin Kramer64aae502010-02-16 10:07:31 +00001893 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001894
Eli Friedman7e4faac2009-08-31 20:06:00 +00001895 if (OrigArg->isTypeDependent())
1896 return false;
1897
Chris Lattner68784ef2010-05-06 05:50:07 +00001898 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001899 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001900 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001901 diag::err_typecheck_call_invalid_unary_fp)
1902 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001903
Chris Lattner68784ef2010-05-06 05:50:07 +00001904 // If this is an implicit conversion from float -> double, remove it.
1905 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1906 Expr *CastArg = Cast->getSubExpr();
1907 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1908 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1909 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001911 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001912 }
1913 }
1914
Eli Friedman7e4faac2009-08-31 20:06:00 +00001915 return false;
1916}
1917
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001918/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1919// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001920ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001921 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001922 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001923 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001924 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1925 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001926
Nate Begemana0110022010-06-08 00:16:34 +00001927 // Determine which of the following types of shufflevector we're checking:
1928 // 1) unary, vector mask: (lhs, mask)
1929 // 2) binary, vector mask: (lhs, rhs, mask)
1930 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1931 QualType resType = TheCall->getArg(0)->getType();
1932 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001933
Douglas Gregorc25f7662009-05-19 22:10:17 +00001934 if (!TheCall->getArg(0)->isTypeDependent() &&
1935 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001936 QualType LHSType = TheCall->getArg(0)->getType();
1937 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001938
Craig Topperbaca3892013-07-29 06:47:04 +00001939 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1940 return ExprError(Diag(TheCall->getLocStart(),
1941 diag::err_shufflevector_non_vector)
1942 << SourceRange(TheCall->getArg(0)->getLocStart(),
1943 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001944
Nate Begemana0110022010-06-08 00:16:34 +00001945 numElements = LHSType->getAs<VectorType>()->getNumElements();
1946 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001947
Nate Begemana0110022010-06-08 00:16:34 +00001948 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1949 // with mask. If so, verify that RHS is an integer vector type with the
1950 // same number of elts as lhs.
1951 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001952 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001953 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001954 return ExprError(Diag(TheCall->getLocStart(),
1955 diag::err_shufflevector_incompatible_vector)
1956 << SourceRange(TheCall->getArg(1)->getLocStart(),
1957 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001958 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001959 return ExprError(Diag(TheCall->getLocStart(),
1960 diag::err_shufflevector_incompatible_vector)
1961 << SourceRange(TheCall->getArg(0)->getLocStart(),
1962 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001963 } else if (numElements != numResElements) {
1964 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001965 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001966 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001967 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001968 }
1969
1970 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001971 if (TheCall->getArg(i)->isTypeDependent() ||
1972 TheCall->getArg(i)->isValueDependent())
1973 continue;
1974
Nate Begemana0110022010-06-08 00:16:34 +00001975 llvm::APSInt Result(32);
1976 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1977 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001978 diag::err_shufflevector_nonconstant_argument)
1979 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001980
Craig Topper50ad5b72013-08-03 17:40:38 +00001981 // Allow -1 which will be translated to undef in the IR.
1982 if (Result.isSigned() && Result.isAllOnesValue())
1983 continue;
1984
Chris Lattner7ab824e2008-08-10 02:05:13 +00001985 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001986 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001987 diag::err_shufflevector_argument_too_large)
1988 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001989 }
1990
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001991 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001992
Chris Lattner7ab824e2008-08-10 02:05:13 +00001993 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001994 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001995 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001996 }
1997
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001998 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1999 TheCall->getCallee()->getLocStart(),
2000 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002001}
Chris Lattner43be2e62007-12-19 23:59:04 +00002002
Hal Finkelc4d7c822013-09-18 03:29:45 +00002003/// SemaConvertVectorExpr - Handle __builtin_convertvector
2004ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2005 SourceLocation BuiltinLoc,
2006 SourceLocation RParenLoc) {
2007 ExprValueKind VK = VK_RValue;
2008 ExprObjectKind OK = OK_Ordinary;
2009 QualType DstTy = TInfo->getType();
2010 QualType SrcTy = E->getType();
2011
2012 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2013 return ExprError(Diag(BuiltinLoc,
2014 diag::err_convertvector_non_vector)
2015 << E->getSourceRange());
2016 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2017 return ExprError(Diag(BuiltinLoc,
2018 diag::err_convertvector_non_vector_type));
2019
2020 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2021 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2022 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2023 if (SrcElts != DstElts)
2024 return ExprError(Diag(BuiltinLoc,
2025 diag::err_convertvector_incompatible_vector)
2026 << E->getSourceRange());
2027 }
2028
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002029 return new (Context)
2030 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002031}
2032
Daniel Dunbarb7257262008-07-21 22:59:13 +00002033/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2034// This is declared to take (const void*, ...) and can take two
2035// optional constant int args.
2036bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002037 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002038
Chris Lattner3b054132008-11-19 05:08:23 +00002039 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002040 return Diag(TheCall->getLocEnd(),
2041 diag::err_typecheck_call_too_many_args_at_most)
2042 << 0 /*function call*/ << 3 << NumArgs
2043 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002044
2045 // Argument 0 is checked for us and the remaining arguments must be
2046 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002047 for (unsigned i = 1; i != NumArgs; ++i)
2048 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002049 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002050
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002051 return false;
2052}
2053
Hal Finkelf0417332014-07-17 14:25:55 +00002054/// SemaBuiltinAssume - Handle __assume (MS Extension).
2055// __assume does not evaluate its arguments, and should warn if its argument
2056// has side effects.
2057bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2058 Expr *Arg = TheCall->getArg(0);
2059 if (Arg->isInstantiationDependent()) return false;
2060
2061 if (Arg->HasSideEffects(Context))
2062 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2063 << Arg->getSourceRange();
2064
2065 return false;
2066}
2067
Eric Christopher8d0c6212010-04-17 02:26:23 +00002068/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2069/// TheCall is a constant expression.
2070bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2071 llvm::APSInt &Result) {
2072 Expr *Arg = TheCall->getArg(ArgNum);
2073 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2074 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2075
2076 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2077
2078 if (!Arg->isIntegerConstantExpr(Result, Context))
2079 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002080 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002081
Chris Lattnerd545ad12009-09-23 06:06:36 +00002082 return false;
2083}
2084
Richard Sandiford28940af2014-04-16 08:47:51 +00002085/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2086/// TheCall is a constant expression in the range [Low, High].
2087bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2088 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002089 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002090
2091 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002092 Expr *Arg = TheCall->getArg(ArgNum);
2093 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002094 return false;
2095
Eric Christopher8d0c6212010-04-17 02:26:23 +00002096 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002098 return true;
2099
Richard Sandiford28940af2014-04-16 08:47:51 +00002100 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002101 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002102 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002103
2104 return false;
2105}
2106
Eli Friedmanc97d0142009-05-03 06:04:26 +00002107/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002108/// This checks that val is a constant 1.
2109bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2110 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002111 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002112
Eric Christopher8d0c6212010-04-17 02:26:23 +00002113 // TODO: This is less than ideal. Overload this to take a value.
2114 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2115 return true;
2116
2117 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002118 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2119 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2120
2121 return false;
2122}
2123
Richard Smithd7293d72013-08-05 18:49:43 +00002124namespace {
2125enum StringLiteralCheckType {
2126 SLCT_NotALiteral,
2127 SLCT_UncheckedLiteral,
2128 SLCT_CheckedLiteral
2129};
2130}
2131
Richard Smith55ce3522012-06-25 20:30:08 +00002132// Determine if an expression is a string literal or constant string.
2133// If this function returns false on the arguments to a function expecting a
2134// format string, we will usually need to emit a warning.
2135// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002136static StringLiteralCheckType
2137checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2138 bool HasVAListArg, unsigned format_idx,
2139 unsigned firstDataArg, Sema::FormatStringType Type,
2140 Sema::VariadicCallType CallType, bool InFunctionCall,
2141 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002142 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002143 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002144 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002145
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002146 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002147
Richard Smithd7293d72013-08-05 18:49:43 +00002148 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002149 // Technically -Wformat-nonliteral does not warn about this case.
2150 // The behavior of printf and friends in this case is implementation
2151 // dependent. Ideally if the format string cannot be null then
2152 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002153 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002154
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002155 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002156 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002157 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002158 // The expression is a literal if both sub-expressions were, and it was
2159 // completely checked only if both sub-expressions were checked.
2160 const AbstractConditionalOperator *C =
2161 cast<AbstractConditionalOperator>(E);
2162 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002163 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002164 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002165 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002166 if (Left == SLCT_NotALiteral)
2167 return SLCT_NotALiteral;
2168 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002169 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002170 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002171 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002172 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002173 }
2174
2175 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002176 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2177 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002178 }
2179
John McCallc07a0c72011-02-17 10:25:35 +00002180 case Stmt::OpaqueValueExprClass:
2181 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2182 E = src;
2183 goto tryAgain;
2184 }
Richard Smith55ce3522012-06-25 20:30:08 +00002185 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002186
Ted Kremeneka8890832011-02-24 23:03:04 +00002187 case Stmt::PredefinedExprClass:
2188 // While __func__, etc., are technically not string literals, they
2189 // cannot contain format specifiers and thus are not a security
2190 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002191 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002192
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002193 case Stmt::DeclRefExprClass: {
2194 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002195
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002196 // As an exception, do not flag errors for variables binding to
2197 // const string literals.
2198 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2199 bool isConstant = false;
2200 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002201
Richard Smithd7293d72013-08-05 18:49:43 +00002202 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2203 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002204 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002205 isConstant = T.isConstant(S.Context) &&
2206 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002207 } else if (T->isObjCObjectPointerType()) {
2208 // In ObjC, there is usually no "const ObjectPointer" type,
2209 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002210 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002213 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002214 if (const Expr *Init = VD->getAnyInitializer()) {
2215 // Look through initializers like const char c[] = { "foo" }
2216 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2217 if (InitList->isStringLiteralInit())
2218 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2219 }
Richard Smithd7293d72013-08-05 18:49:43 +00002220 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002221 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002222 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002223 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002224 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Anders Carlssonb012ca92009-06-28 19:55:58 +00002227 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2228 // special check to see if the format string is a function parameter
2229 // of the function calling the printf function. If the function
2230 // has an attribute indicating it is a printf-like function, then we
2231 // should suppress warnings concerning non-literals being used in a call
2232 // to a vprintf function. For example:
2233 //
2234 // void
2235 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2236 // va_list ap;
2237 // va_start(ap, fmt);
2238 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2239 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002240 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002241 if (HasVAListArg) {
2242 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2243 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2244 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002245 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002246 // adjust for implicit parameter
2247 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2248 if (MD->isInstance())
2249 ++PVIndex;
2250 // We also check if the formats are compatible.
2251 // We can't pass a 'scanf' string to a 'printf' function.
2252 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002253 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002254 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002255 }
2256 }
2257 }
2258 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002259 }
Mike Stump11289f42009-09-09 15:08:12 +00002260
Richard Smith55ce3522012-06-25 20:30:08 +00002261 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002262 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002263
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002264 case Stmt::CallExprClass:
2265 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002266 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002267 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2268 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2269 unsigned ArgIndex = FA->getFormatIdx();
2270 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2271 if (MD->isInstance())
2272 --ArgIndex;
2273 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002274
Richard Smithd7293d72013-08-05 18:49:43 +00002275 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002276 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002277 Type, CallType, InFunctionCall,
2278 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002279 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2280 unsigned BuiltinID = FD->getBuiltinID();
2281 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2282 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2283 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002284 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002285 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002286 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002287 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002288 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002289 }
2290 }
Mike Stump11289f42009-09-09 15:08:12 +00002291
Richard Smith55ce3522012-06-25 20:30:08 +00002292 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002293 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002294 case Stmt::ObjCStringLiteralClass:
2295 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002296 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002297
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002298 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002299 StrE = ObjCFExpr->getString();
2300 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002301 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002302
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002303 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002304 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2305 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002306 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Richard Smith55ce3522012-06-25 20:30:08 +00002309 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002312 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002313 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002314 }
2315}
2316
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002317Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002318 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002319 .Case("scanf", FST_Scanf)
2320 .Cases("printf", "printf0", FST_Printf)
2321 .Cases("NSString", "CFString", FST_NSString)
2322 .Case("strftime", FST_Strftime)
2323 .Case("strfmon", FST_Strfmon)
2324 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2325 .Default(FST_Unknown);
2326}
2327
Jordan Rose3e0ec582012-07-19 18:10:23 +00002328/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002329/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002330/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002331bool Sema::CheckFormatArguments(const FormatAttr *Format,
2332 ArrayRef<const Expr *> Args,
2333 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002334 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002335 SourceLocation Loc, SourceRange Range,
2336 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002337 FormatStringInfo FSI;
2338 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002339 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002340 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002341 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002342 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002343}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002344
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002345bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002346 bool HasVAListArg, unsigned format_idx,
2347 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002348 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002349 SourceLocation Loc, SourceRange Range,
2350 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002351 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002352 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002353 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002354 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002357 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002358
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002359 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002360 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002361 // Dynamically generated format strings are difficult to
2362 // automatically vet at compile time. Requiring that format strings
2363 // are string literals: (1) permits the checking of format strings by
2364 // the compiler and thereby (2) can practically remove the source of
2365 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002366
Mike Stump11289f42009-09-09 15:08:12 +00002367 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002368 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002369 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002370 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002371 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002372 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2373 format_idx, firstDataArg, Type, CallType,
2374 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002375 if (CT != SLCT_NotALiteral)
2376 // Literal format string found, check done!
2377 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002378
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002379 // Strftime is particular as it always uses a single 'time' argument,
2380 // so it is safe to pass a non-literal string.
2381 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002382 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002383
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002384 // Do not emit diag when the string param is a macro expansion and the
2385 // format is either NSString or CFString. This is a hack to prevent
2386 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2387 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002388 if (Type == FST_NSString &&
2389 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002390 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002391
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002392 // If there are no arguments specified, warn with -Wformat-security, otherwise
2393 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002394 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002395 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002396 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002397 << OrigFormatExpr->getSourceRange();
2398 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002399 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002400 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002401 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002402 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002403}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002404
Ted Kremenekab278de2010-01-28 23:39:18 +00002405namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002406class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2407protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002408 Sema &S;
2409 const StringLiteral *FExpr;
2410 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002411 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002412 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002413 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002414 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002415 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002416 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002417 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002418 bool usesPositionalArgs;
2419 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002420 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002421 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002422 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002423public:
Ted Kremenek02087932010-07-16 02:11:22 +00002424 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002425 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002426 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002427 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002428 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002429 Sema::VariadicCallType callType,
2430 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002431 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002432 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2433 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002434 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002435 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002436 inFunctionCall(inFunctionCall), CallType(callType),
2437 CheckedVarArgs(CheckedVarArgs) {
2438 CoveredArgs.resize(numDataArgs);
2439 CoveredArgs.reset();
2440 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002441
Ted Kremenek019d2242010-01-29 01:50:07 +00002442 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002443
Ted Kremenek02087932010-07-16 02:11:22 +00002444 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002445 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002446
Jordan Rose92303592012-09-08 04:00:03 +00002447 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002448 const analyze_format_string::FormatSpecifier &FS,
2449 const analyze_format_string::ConversionSpecifier &CS,
2450 const char *startSpecifier, unsigned specifierLen,
2451 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002452
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002453 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002454 const analyze_format_string::FormatSpecifier &FS,
2455 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002456
2457 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002458 const analyze_format_string::ConversionSpecifier &CS,
2459 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002460
Craig Toppere14c0f82014-03-12 04:55:44 +00002461 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002462
Craig Toppere14c0f82014-03-12 04:55:44 +00002463 void HandleInvalidPosition(const char *startSpecifier,
2464 unsigned specifierLen,
2465 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002466
Craig Toppere14c0f82014-03-12 04:55:44 +00002467 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002468
Craig Toppere14c0f82014-03-12 04:55:44 +00002469 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002470
Richard Trieu03cf7b72011-10-28 00:41:25 +00002471 template <typename Range>
2472 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2473 const Expr *ArgumentExpr,
2474 PartialDiagnostic PDiag,
2475 SourceLocation StringLoc,
2476 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002477 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002478
Ted Kremenek02087932010-07-16 02:11:22 +00002479protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002480 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2481 const char *startSpec,
2482 unsigned specifierLen,
2483 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002484
2485 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2486 const char *startSpec,
2487 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002488
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002489 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002490 CharSourceRange getSpecifierRange(const char *startSpecifier,
2491 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002492 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002493
Ted Kremenek5739de72010-01-29 01:06:55 +00002494 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002495
2496 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2497 const analyze_format_string::ConversionSpecifier &CS,
2498 const char *startSpecifier, unsigned specifierLen,
2499 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002500
2501 template <typename Range>
2502 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2503 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002504 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002505};
2506}
2507
Ted Kremenek02087932010-07-16 02:11:22 +00002508SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002509 return OrigFormatExpr->getSourceRange();
2510}
2511
Ted Kremenek02087932010-07-16 02:11:22 +00002512CharSourceRange CheckFormatHandler::
2513getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002514 SourceLocation Start = getLocationOfByte(startSpecifier);
2515 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2516
2517 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002518 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002519
2520 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002521}
2522
Ted Kremenek02087932010-07-16 02:11:22 +00002523SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002524 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002525}
2526
Ted Kremenek02087932010-07-16 02:11:22 +00002527void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2528 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002529 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2530 getLocationOfByte(startSpecifier),
2531 /*IsStringLocation*/true,
2532 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002533}
2534
Jordan Rose92303592012-09-08 04:00:03 +00002535void CheckFormatHandler::HandleInvalidLengthModifier(
2536 const analyze_format_string::FormatSpecifier &FS,
2537 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002538 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002539 using namespace analyze_format_string;
2540
2541 const LengthModifier &LM = FS.getLengthModifier();
2542 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2543
2544 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002545 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002546 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002547 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002548 getLocationOfByte(LM.getStart()),
2549 /*IsStringLocation*/true,
2550 getSpecifierRange(startSpecifier, specifierLen));
2551
2552 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2553 << FixedLM->toString()
2554 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2555
2556 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002557 FixItHint Hint;
2558 if (DiagID == diag::warn_format_nonsensical_length)
2559 Hint = FixItHint::CreateRemoval(LMRange);
2560
2561 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002562 getLocationOfByte(LM.getStart()),
2563 /*IsStringLocation*/true,
2564 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002565 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002566 }
2567}
2568
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002569void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002570 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002571 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002572 using namespace analyze_format_string;
2573
2574 const LengthModifier &LM = FS.getLengthModifier();
2575 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2576
2577 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002578 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002579 if (FixedLM) {
2580 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2581 << LM.toString() << 0,
2582 getLocationOfByte(LM.getStart()),
2583 /*IsStringLocation*/true,
2584 getSpecifierRange(startSpecifier, specifierLen));
2585
2586 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2587 << FixedLM->toString()
2588 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2589
2590 } else {
2591 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2592 << LM.toString() << 0,
2593 getLocationOfByte(LM.getStart()),
2594 /*IsStringLocation*/true,
2595 getSpecifierRange(startSpecifier, specifierLen));
2596 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002597}
2598
2599void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2600 const analyze_format_string::ConversionSpecifier &CS,
2601 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002602 using namespace analyze_format_string;
2603
2604 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002605 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002606 if (FixedCS) {
2607 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2608 << CS.toString() << /*conversion specifier*/1,
2609 getLocationOfByte(CS.getStart()),
2610 /*IsStringLocation*/true,
2611 getSpecifierRange(startSpecifier, specifierLen));
2612
2613 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2614 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2615 << FixedCS->toString()
2616 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2617 } else {
2618 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2619 << CS.toString() << /*conversion specifier*/1,
2620 getLocationOfByte(CS.getStart()),
2621 /*IsStringLocation*/true,
2622 getSpecifierRange(startSpecifier, specifierLen));
2623 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002624}
2625
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002626void CheckFormatHandler::HandlePosition(const char *startPos,
2627 unsigned posLen) {
2628 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2629 getLocationOfByte(startPos),
2630 /*IsStringLocation*/true,
2631 getSpecifierRange(startPos, posLen));
2632}
2633
Ted Kremenekd1668192010-02-27 01:41:03 +00002634void
Ted Kremenek02087932010-07-16 02:11:22 +00002635CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2636 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002637 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2638 << (unsigned) p,
2639 getLocationOfByte(startPos), /*IsStringLocation*/true,
2640 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002641}
2642
Ted Kremenek02087932010-07-16 02:11:22 +00002643void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002644 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002645 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2646 getLocationOfByte(startPos),
2647 /*IsStringLocation*/true,
2648 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002649}
2650
Ted Kremenek02087932010-07-16 02:11:22 +00002651void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002652 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002653 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002654 EmitFormatDiagnostic(
2655 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2656 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2657 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002658 }
Ted Kremenek02087932010-07-16 02:11:22 +00002659}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002660
Jordan Rose58bbe422012-07-19 18:10:08 +00002661// Note that this may return NULL if there was an error parsing or building
2662// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002663const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002664 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002665}
2666
2667void CheckFormatHandler::DoneProcessing() {
2668 // Does the number of data arguments exceed the number of
2669 // format conversions in the format string?
2670 if (!HasVAListArg) {
2671 // Find any arguments that weren't covered.
2672 CoveredArgs.flip();
2673 signed notCoveredArg = CoveredArgs.find_first();
2674 if (notCoveredArg >= 0) {
2675 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002676 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2677 SourceLocation Loc = E->getLocStart();
2678 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2679 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2680 Loc, /*IsStringLocation*/false,
2681 getFormatStringRange());
2682 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002683 }
Ted Kremenek02087932010-07-16 02:11:22 +00002684 }
2685 }
2686}
2687
Ted Kremenekce815422010-07-19 21:25:57 +00002688bool
2689CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2690 SourceLocation Loc,
2691 const char *startSpec,
2692 unsigned specifierLen,
2693 const char *csStart,
2694 unsigned csLen) {
2695
2696 bool keepGoing = true;
2697 if (argIndex < NumDataArgs) {
2698 // Consider the argument coverered, even though the specifier doesn't
2699 // make sense.
2700 CoveredArgs.set(argIndex);
2701 }
2702 else {
2703 // If argIndex exceeds the number of data arguments we
2704 // don't issue a warning because that is just a cascade of warnings (and
2705 // they may have intended '%%' anyway). We don't want to continue processing
2706 // the format string after this point, however, as we will like just get
2707 // gibberish when trying to match arguments.
2708 keepGoing = false;
2709 }
2710
Richard Trieu03cf7b72011-10-28 00:41:25 +00002711 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2712 << StringRef(csStart, csLen),
2713 Loc, /*IsStringLocation*/true,
2714 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002715
2716 return keepGoing;
2717}
2718
Richard Trieu03cf7b72011-10-28 00:41:25 +00002719void
2720CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2721 const char *startSpec,
2722 unsigned specifierLen) {
2723 EmitFormatDiagnostic(
2724 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2725 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2726}
2727
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002728bool
2729CheckFormatHandler::CheckNumArgs(
2730 const analyze_format_string::FormatSpecifier &FS,
2731 const analyze_format_string::ConversionSpecifier &CS,
2732 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2733
2734 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002735 PartialDiagnostic PDiag = FS.usesPositionalArg()
2736 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2737 << (argIndex+1) << NumDataArgs)
2738 : S.PDiag(diag::warn_printf_insufficient_data_args);
2739 EmitFormatDiagnostic(
2740 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2741 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002742 return false;
2743 }
2744 return true;
2745}
2746
Richard Trieu03cf7b72011-10-28 00:41:25 +00002747template<typename Range>
2748void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2749 SourceLocation Loc,
2750 bool IsStringLocation,
2751 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002752 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002753 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002754 Loc, IsStringLocation, StringRange, FixIt);
2755}
2756
2757/// \brief If the format string is not within the funcion call, emit a note
2758/// so that the function call and string are in diagnostic messages.
2759///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002760/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002761/// call and only one diagnostic message will be produced. Otherwise, an
2762/// extra note will be emitted pointing to location of the format string.
2763///
2764/// \param ArgumentExpr the expression that is passed as the format string
2765/// argument in the function call. Used for getting locations when two
2766/// diagnostics are emitted.
2767///
2768/// \param PDiag the callee should already have provided any strings for the
2769/// diagnostic message. This function only adds locations and fixits
2770/// to diagnostics.
2771///
2772/// \param Loc primary location for diagnostic. If two diagnostics are
2773/// required, one will be at Loc and a new SourceLocation will be created for
2774/// the other one.
2775///
2776/// \param IsStringLocation if true, Loc points to the format string should be
2777/// used for the note. Otherwise, Loc points to the argument list and will
2778/// be used with PDiag.
2779///
2780/// \param StringRange some or all of the string to highlight. This is
2781/// templated so it can accept either a CharSourceRange or a SourceRange.
2782///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002783/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002784template<typename Range>
2785void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2786 const Expr *ArgumentExpr,
2787 PartialDiagnostic PDiag,
2788 SourceLocation Loc,
2789 bool IsStringLocation,
2790 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002791 ArrayRef<FixItHint> FixIt) {
2792 if (InFunctionCall) {
2793 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2794 D << StringRange;
2795 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2796 I != E; ++I) {
2797 D << *I;
2798 }
2799 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002800 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2801 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002802
2803 const Sema::SemaDiagnosticBuilder &Note =
2804 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2805 diag::note_format_string_defined);
2806
2807 Note << StringRange;
2808 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2809 I != E; ++I) {
2810 Note << *I;
2811 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002812 }
2813}
2814
Ted Kremenek02087932010-07-16 02:11:22 +00002815//===--- CHECK: Printf format string checking ------------------------------===//
2816
2817namespace {
2818class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002819 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002820public:
2821 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2822 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002823 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002824 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002825 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002826 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002827 Sema::VariadicCallType CallType,
2828 llvm::SmallBitVector &CheckedVarArgs)
2829 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2830 numDataArgs, beg, hasVAListArg, Args,
2831 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2832 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002833 {}
2834
Craig Toppere14c0f82014-03-12 04:55:44 +00002835
Ted Kremenek02087932010-07-16 02:11:22 +00002836 bool HandleInvalidPrintfConversionSpecifier(
2837 const analyze_printf::PrintfSpecifier &FS,
2838 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002839 unsigned specifierLen) override;
2840
Ted Kremenek02087932010-07-16 02:11:22 +00002841 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2842 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002843 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002844 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2845 const char *StartSpecifier,
2846 unsigned SpecifierLen,
2847 const Expr *E);
2848
Ted Kremenek02087932010-07-16 02:11:22 +00002849 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2850 const char *startSpecifier, unsigned specifierLen);
2851 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2852 const analyze_printf::OptionalAmount &Amt,
2853 unsigned type,
2854 const char *startSpecifier, unsigned specifierLen);
2855 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2856 const analyze_printf::OptionalFlag &flag,
2857 const char *startSpecifier, unsigned specifierLen);
2858 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2859 const analyze_printf::OptionalFlag &ignoredFlag,
2860 const analyze_printf::OptionalFlag &flag,
2861 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002862 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002863 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002864
Ted Kremenek02087932010-07-16 02:11:22 +00002865};
2866}
2867
2868bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2869 const analyze_printf::PrintfSpecifier &FS,
2870 const char *startSpecifier,
2871 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002872 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002873 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002874
Ted Kremenekce815422010-07-19 21:25:57 +00002875 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2876 getLocationOfByte(CS.getStart()),
2877 startSpecifier, specifierLen,
2878 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002879}
2880
Ted Kremenek02087932010-07-16 02:11:22 +00002881bool CheckPrintfHandler::HandleAmount(
2882 const analyze_format_string::OptionalAmount &Amt,
2883 unsigned k, const char *startSpecifier,
2884 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002885
2886 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002887 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002888 unsigned argIndex = Amt.getArgIndex();
2889 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002890 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2891 << k,
2892 getLocationOfByte(Amt.getStart()),
2893 /*IsStringLocation*/true,
2894 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002895 // Don't do any more checking. We will just emit
2896 // spurious errors.
2897 return false;
2898 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002899
Ted Kremenek5739de72010-01-29 01:06:55 +00002900 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002901 // Although not in conformance with C99, we also allow the argument to be
2902 // an 'unsigned int' as that is a reasonably safe case. GCC also
2903 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002904 CoveredArgs.set(argIndex);
2905 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002906 if (!Arg)
2907 return false;
2908
Ted Kremenek5739de72010-01-29 01:06:55 +00002909 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002910
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002911 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2912 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002913
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002914 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002916 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002917 << T << Arg->getSourceRange(),
2918 getLocationOfByte(Amt.getStart()),
2919 /*IsStringLocation*/true,
2920 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002921 // Don't do any more checking. We will just emit
2922 // spurious errors.
2923 return false;
2924 }
2925 }
2926 }
2927 return true;
2928}
Ted Kremenek5739de72010-01-29 01:06:55 +00002929
Tom Careb49ec692010-06-17 19:00:27 +00002930void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002931 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002932 const analyze_printf::OptionalAmount &Amt,
2933 unsigned type,
2934 const char *startSpecifier,
2935 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002936 const analyze_printf::PrintfConversionSpecifier &CS =
2937 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002938
Richard Trieu03cf7b72011-10-28 00:41:25 +00002939 FixItHint fixit =
2940 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2941 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2942 Amt.getConstantLength()))
2943 : FixItHint();
2944
2945 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2946 << type << CS.toString(),
2947 getLocationOfByte(Amt.getStart()),
2948 /*IsStringLocation*/true,
2949 getSpecifierRange(startSpecifier, specifierLen),
2950 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002951}
2952
Ted Kremenek02087932010-07-16 02:11:22 +00002953void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002954 const analyze_printf::OptionalFlag &flag,
2955 const char *startSpecifier,
2956 unsigned specifierLen) {
2957 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002958 const analyze_printf::PrintfConversionSpecifier &CS =
2959 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002960 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2961 << flag.toString() << CS.toString(),
2962 getLocationOfByte(flag.getPosition()),
2963 /*IsStringLocation*/true,
2964 getSpecifierRange(startSpecifier, specifierLen),
2965 FixItHint::CreateRemoval(
2966 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002967}
2968
2969void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002970 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002971 const analyze_printf::OptionalFlag &ignoredFlag,
2972 const analyze_printf::OptionalFlag &flag,
2973 const char *startSpecifier,
2974 unsigned specifierLen) {
2975 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002976 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2977 << ignoredFlag.toString() << flag.toString(),
2978 getLocationOfByte(ignoredFlag.getPosition()),
2979 /*IsStringLocation*/true,
2980 getSpecifierRange(startSpecifier, specifierLen),
2981 FixItHint::CreateRemoval(
2982 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002983}
2984
Richard Smith55ce3522012-06-25 20:30:08 +00002985// Determines if the specified is a C++ class or struct containing
2986// a member with the specified name and kind (e.g. a CXXMethodDecl named
2987// "c_str()").
2988template<typename MemberKind>
2989static llvm::SmallPtrSet<MemberKind*, 1>
2990CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2991 const RecordType *RT = Ty->getAs<RecordType>();
2992 llvm::SmallPtrSet<MemberKind*, 1> Results;
2993
2994 if (!RT)
2995 return Results;
2996 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002997 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002998 return Results;
2999
Alp Tokerb6cc5922014-05-03 03:45:55 +00003000 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003001 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003002 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003003
3004 // We just need to include all members of the right kind turned up by the
3005 // filter, at this point.
3006 if (S.LookupQualifiedName(R, RT->getDecl()))
3007 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3008 NamedDecl *decl = (*I)->getUnderlyingDecl();
3009 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3010 Results.insert(FK);
3011 }
3012 return Results;
3013}
3014
Richard Smith2868a732014-02-28 01:36:39 +00003015/// Check if we could call '.c_str()' on an object.
3016///
3017/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3018/// allow the call, or if it would be ambiguous).
3019bool Sema::hasCStrMethod(const Expr *E) {
3020 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3021 MethodSet Results =
3022 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3023 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3024 MI != ME; ++MI)
3025 if ((*MI)->getMinRequiredArguments() == 0)
3026 return true;
3027 return false;
3028}
3029
Richard Smith55ce3522012-06-25 20:30:08 +00003030// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003031// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003032// Returns true when a c_str() conversion method is found.
3033bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003034 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003035 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3036
3037 MethodSet Results =
3038 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3039
3040 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3041 MI != ME; ++MI) {
3042 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003043 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003044 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003045 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003046 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003047 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3048 << "c_str()"
3049 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3050 return true;
3051 }
3052 }
3053
3054 return false;
3055}
3056
Ted Kremenekab278de2010-01-28 23:39:18 +00003057bool
Ted Kremenek02087932010-07-16 02:11:22 +00003058CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003059 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003060 const char *startSpecifier,
3061 unsigned specifierLen) {
3062
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003063 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003064 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003065 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003066
Ted Kremenek6cd69422010-07-19 22:01:06 +00003067 if (FS.consumesDataArgument()) {
3068 if (atFirstArg) {
3069 atFirstArg = false;
3070 usesPositionalArgs = FS.usesPositionalArg();
3071 }
3072 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003073 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3074 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003075 return false;
3076 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003077 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003078
Ted Kremenekd1668192010-02-27 01:41:03 +00003079 // First check if the field width, precision, and conversion specifier
3080 // have matching data arguments.
3081 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3082 startSpecifier, specifierLen)) {
3083 return false;
3084 }
3085
3086 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3087 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003088 return false;
3089 }
3090
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003091 if (!CS.consumesDataArgument()) {
3092 // FIXME: Technically specifying a precision or field width here
3093 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003094 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003095 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003096
Ted Kremenek4a49d982010-02-26 19:18:41 +00003097 // Consume the argument.
3098 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003099 if (argIndex < NumDataArgs) {
3100 // The check to see if the argIndex is valid will come later.
3101 // We set the bit here because we may exit early from this
3102 // function if we encounter some other error.
3103 CoveredArgs.set(argIndex);
3104 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003105
3106 // Check for using an Objective-C specific conversion specifier
3107 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003108 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003109 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3110 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003111 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003112
Tom Careb49ec692010-06-17 19:00:27 +00003113 // Check for invalid use of field width
3114 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003115 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003116 startSpecifier, specifierLen);
3117 }
3118
3119 // Check for invalid use of precision
3120 if (!FS.hasValidPrecision()) {
3121 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3122 startSpecifier, specifierLen);
3123 }
3124
3125 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003126 if (!FS.hasValidThousandsGroupingPrefix())
3127 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003128 if (!FS.hasValidLeadingZeros())
3129 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3130 if (!FS.hasValidPlusPrefix())
3131 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003132 if (!FS.hasValidSpacePrefix())
3133 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003134 if (!FS.hasValidAlternativeForm())
3135 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3136 if (!FS.hasValidLeftJustified())
3137 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3138
3139 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003140 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3141 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3142 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003143 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3144 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3145 startSpecifier, specifierLen);
3146
3147 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003148 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003149 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3150 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003151 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003152 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003153 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003154 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3155 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003156
Jordan Rose92303592012-09-08 04:00:03 +00003157 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3158 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3159
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003160 // The remaining checks depend on the data arguments.
3161 if (HasVAListArg)
3162 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003163
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003164 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003165 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003166
Jordan Rose58bbe422012-07-19 18:10:08 +00003167 const Expr *Arg = getDataArg(argIndex);
3168 if (!Arg)
3169 return true;
3170
3171 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003172}
3173
Jordan Roseaee34382012-09-05 22:56:26 +00003174static bool requiresParensToAddCast(const Expr *E) {
3175 // FIXME: We should have a general way to reason about operator
3176 // precedence and whether parens are actually needed here.
3177 // Take care of a few common cases where they aren't.
3178 const Expr *Inside = E->IgnoreImpCasts();
3179 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3180 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3181
3182 switch (Inside->getStmtClass()) {
3183 case Stmt::ArraySubscriptExprClass:
3184 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003185 case Stmt::CharacterLiteralClass:
3186 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003187 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003188 case Stmt::FloatingLiteralClass:
3189 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003190 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003191 case Stmt::ObjCArrayLiteralClass:
3192 case Stmt::ObjCBoolLiteralExprClass:
3193 case Stmt::ObjCBoxedExprClass:
3194 case Stmt::ObjCDictionaryLiteralClass:
3195 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003196 case Stmt::ObjCIvarRefExprClass:
3197 case Stmt::ObjCMessageExprClass:
3198 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003199 case Stmt::ObjCStringLiteralClass:
3200 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003201 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003202 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003203 case Stmt::UnaryOperatorClass:
3204 return false;
3205 default:
3206 return true;
3207 }
3208}
3209
Richard Smith55ce3522012-06-25 20:30:08 +00003210bool
3211CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3212 const char *StartSpecifier,
3213 unsigned SpecifierLen,
3214 const Expr *E) {
3215 using namespace analyze_format_string;
3216 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003217 // Now type check the data expression that matches the
3218 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003219 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3220 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003221 if (!AT.isValid())
3222 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003223
Jordan Rose598ec092012-12-05 18:44:40 +00003224 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003225 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3226 ExprTy = TET->getUnderlyingExpr()->getType();
3227 }
3228
Jordan Rose598ec092012-12-05 18:44:40 +00003229 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003230 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003231
Jordan Rose22b74712012-09-05 22:56:19 +00003232 // Look through argument promotions for our error message's reported type.
3233 // This includes the integral and floating promotions, but excludes array
3234 // and function pointer decay; seeing that an argument intended to be a
3235 // string has type 'char [6]' is probably more confusing than 'char *'.
3236 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3237 if (ICE->getCastKind() == CK_IntegralCast ||
3238 ICE->getCastKind() == CK_FloatingCast) {
3239 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003240 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003241
3242 // Check if we didn't match because of an implicit cast from a 'char'
3243 // or 'short' to an 'int'. This is done because printf is a varargs
3244 // function.
3245 if (ICE->getType() == S.Context.IntTy ||
3246 ICE->getType() == S.Context.UnsignedIntTy) {
3247 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003248 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003249 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003250 }
Jordan Rose98709982012-06-04 22:48:57 +00003251 }
Jordan Rose598ec092012-12-05 18:44:40 +00003252 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3253 // Special case for 'a', which has type 'int' in C.
3254 // Note, however, that we do /not/ want to treat multibyte constants like
3255 // 'MooV' as characters! This form is deprecated but still exists.
3256 if (ExprTy == S.Context.IntTy)
3257 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3258 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003259 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003260
Jordan Rosebc53ed12014-05-31 04:12:14 +00003261 // Look through enums to their underlying type.
3262 bool IsEnum = false;
3263 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3264 ExprTy = EnumTy->getDecl()->getIntegerType();
3265 IsEnum = true;
3266 }
3267
Jordan Rose0e5badd2012-12-05 18:44:49 +00003268 // %C in an Objective-C context prints a unichar, not a wchar_t.
3269 // If the argument is an integer of some kind, believe the %C and suggest
3270 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003271 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003272 if (ObjCContext &&
3273 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3274 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3275 !ExprTy->isCharType()) {
3276 // 'unichar' is defined as a typedef of unsigned short, but we should
3277 // prefer using the typedef if it is visible.
3278 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003279
3280 // While we are here, check if the value is an IntegerLiteral that happens
3281 // to be within the valid range.
3282 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3283 const llvm::APInt &V = IL->getValue();
3284 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3285 return true;
3286 }
3287
Jordan Rose0e5badd2012-12-05 18:44:49 +00003288 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3289 Sema::LookupOrdinaryName);
3290 if (S.LookupName(Result, S.getCurScope())) {
3291 NamedDecl *ND = Result.getFoundDecl();
3292 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3293 if (TD->getUnderlyingType() == IntendedTy)
3294 IntendedTy = S.Context.getTypedefType(TD);
3295 }
3296 }
3297 }
3298
3299 // Special-case some of Darwin's platform-independence types by suggesting
3300 // casts to primitive types that are known to be large enough.
3301 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003302 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003303 // Use a 'while' to peel off layers of typedefs.
3304 QualType TyTy = IntendedTy;
3305 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003306 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003307 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003308 .Case("NSInteger", S.Context.LongTy)
3309 .Case("NSUInteger", S.Context.UnsignedLongTy)
3310 .Case("SInt32", S.Context.IntTy)
3311 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003312 .Default(QualType());
3313
3314 if (!CastTy.isNull()) {
3315 ShouldNotPrintDirectly = true;
3316 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003317 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003318 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003319 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003320 }
3321 }
3322
Jordan Rose22b74712012-09-05 22:56:19 +00003323 // We may be able to offer a FixItHint if it is a supported type.
3324 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003325 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003326 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003327
Jordan Rose22b74712012-09-05 22:56:19 +00003328 if (success) {
3329 // Get the fix string from the fixed format specifier
3330 SmallString<16> buf;
3331 llvm::raw_svector_ostream os(buf);
3332 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003333
Jordan Roseaee34382012-09-05 22:56:26 +00003334 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3335
Jordan Rose0e5badd2012-12-05 18:44:49 +00003336 if (IntendedTy == ExprTy) {
3337 // In this case, the specifier is wrong and should be changed to match
3338 // the argument.
3339 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003340 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3341 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003342 << E->getSourceRange(),
3343 E->getLocStart(),
3344 /*IsStringLocation*/false,
3345 SpecRange,
3346 FixItHint::CreateReplacement(SpecRange, os.str()));
3347
3348 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003349 // The canonical type for formatting this value is different from the
3350 // actual type of the expression. (This occurs, for example, with Darwin's
3351 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3352 // should be printed as 'long' for 64-bit compatibility.)
3353 // Rather than emitting a normal format/argument mismatch, we want to
3354 // add a cast to the recommended type (and correct the format string
3355 // if necessary).
3356 SmallString<16> CastBuf;
3357 llvm::raw_svector_ostream CastFix(CastBuf);
3358 CastFix << "(";
3359 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3360 CastFix << ")";
3361
3362 SmallVector<FixItHint,4> Hints;
3363 if (!AT.matchesType(S.Context, IntendedTy))
3364 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3365
3366 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3367 // If there's already a cast present, just replace it.
3368 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3369 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3370
3371 } else if (!requiresParensToAddCast(E)) {
3372 // If the expression has high enough precedence,
3373 // just write the C-style cast.
3374 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3375 CastFix.str()));
3376 } else {
3377 // Otherwise, add parens around the expression as well as the cast.
3378 CastFix << "(";
3379 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3380 CastFix.str()));
3381
Alp Tokerb6cc5922014-05-03 03:45:55 +00003382 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003383 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3384 }
3385
Jordan Rose0e5badd2012-12-05 18:44:49 +00003386 if (ShouldNotPrintDirectly) {
3387 // The expression has a type that should not be printed directly.
3388 // We extract the name from the typedef because we don't want to show
3389 // the underlying type in the diagnostic.
3390 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003391
Jordan Rose0e5badd2012-12-05 18:44:49 +00003392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003393 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003394 << E->getSourceRange(),
3395 E->getLocStart(), /*IsStringLocation=*/false,
3396 SpecRange, Hints);
3397 } else {
3398 // In this case, the expression could be printed using a different
3399 // specifier, but we've decided that the specifier is probably correct
3400 // and we should cast instead. Just use the normal warning message.
3401 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003402 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3403 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003404 << E->getSourceRange(),
3405 E->getLocStart(), /*IsStringLocation*/false,
3406 SpecRange, Hints);
3407 }
Jordan Roseaee34382012-09-05 22:56:26 +00003408 }
Jordan Rose22b74712012-09-05 22:56:19 +00003409 } else {
3410 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3411 SpecifierLen);
3412 // Since the warning for passing non-POD types to variadic functions
3413 // was deferred until now, we emit a warning for non-POD
3414 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003415 switch (S.isValidVarArgType(ExprTy)) {
3416 case Sema::VAK_Valid:
3417 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003418 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003419 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3420 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003421 << CSR
3422 << E->getSourceRange(),
3423 E->getLocStart(), /*IsStringLocation*/false, CSR);
3424 break;
3425
3426 case Sema::VAK_Undefined:
3427 EmitFormatDiagnostic(
3428 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003429 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003430 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003431 << CallType
3432 << AT.getRepresentativeTypeName(S.Context)
3433 << CSR
3434 << E->getSourceRange(),
3435 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003436 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003437 break;
3438
3439 case Sema::VAK_Invalid:
3440 if (ExprTy->isObjCObjectType())
3441 EmitFormatDiagnostic(
3442 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3443 << S.getLangOpts().CPlusPlus11
3444 << ExprTy
3445 << CallType
3446 << AT.getRepresentativeTypeName(S.Context)
3447 << CSR
3448 << E->getSourceRange(),
3449 E->getLocStart(), /*IsStringLocation*/false, CSR);
3450 else
3451 // FIXME: If this is an initializer list, suggest removing the braces
3452 // or inserting a cast to the target type.
3453 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3454 << isa<InitListExpr>(E) << ExprTy << CallType
3455 << AT.getRepresentativeTypeName(S.Context)
3456 << E->getSourceRange();
3457 break;
3458 }
3459
3460 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3461 "format string specifier index out of range");
3462 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003463 }
3464
Ted Kremenekab278de2010-01-28 23:39:18 +00003465 return true;
3466}
3467
Ted Kremenek02087932010-07-16 02:11:22 +00003468//===--- CHECK: Scanf format string checking ------------------------------===//
3469
3470namespace {
3471class CheckScanfHandler : public CheckFormatHandler {
3472public:
3473 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3474 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003475 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003476 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003477 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003478 Sema::VariadicCallType CallType,
3479 llvm::SmallBitVector &CheckedVarArgs)
3480 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3481 numDataArgs, beg, hasVAListArg,
3482 Args, formatIdx, inFunctionCall, CallType,
3483 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003484 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003485
3486 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3487 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003488 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003489
3490 bool HandleInvalidScanfConversionSpecifier(
3491 const analyze_scanf::ScanfSpecifier &FS,
3492 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003493 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003494
Craig Toppere14c0f82014-03-12 04:55:44 +00003495 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003496};
Ted Kremenek019d2242010-01-29 01:50:07 +00003497}
Ted Kremenekab278de2010-01-28 23:39:18 +00003498
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003499void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3500 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003501 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3502 getLocationOfByte(end), /*IsStringLocation*/true,
3503 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003504}
3505
Ted Kremenekce815422010-07-19 21:25:57 +00003506bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3507 const analyze_scanf::ScanfSpecifier &FS,
3508 const char *startSpecifier,
3509 unsigned specifierLen) {
3510
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003511 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003512 FS.getConversionSpecifier();
3513
3514 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3515 getLocationOfByte(CS.getStart()),
3516 startSpecifier, specifierLen,
3517 CS.getStart(), CS.getLength());
3518}
3519
Ted Kremenek02087932010-07-16 02:11:22 +00003520bool CheckScanfHandler::HandleScanfSpecifier(
3521 const analyze_scanf::ScanfSpecifier &FS,
3522 const char *startSpecifier,
3523 unsigned specifierLen) {
3524
3525 using namespace analyze_scanf;
3526 using namespace analyze_format_string;
3527
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003528 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003529
Ted Kremenek6cd69422010-07-19 22:01:06 +00003530 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3531 // be used to decide if we are using positional arguments consistently.
3532 if (FS.consumesDataArgument()) {
3533 if (atFirstArg) {
3534 atFirstArg = false;
3535 usesPositionalArgs = FS.usesPositionalArg();
3536 }
3537 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003538 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3539 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003540 return false;
3541 }
Ted Kremenek02087932010-07-16 02:11:22 +00003542 }
3543
3544 // Check if the field with is non-zero.
3545 const OptionalAmount &Amt = FS.getFieldWidth();
3546 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3547 if (Amt.getConstantAmount() == 0) {
3548 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3549 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003550 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3551 getLocationOfByte(Amt.getStart()),
3552 /*IsStringLocation*/true, R,
3553 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003554 }
3555 }
3556
3557 if (!FS.consumesDataArgument()) {
3558 // FIXME: Technically specifying a precision or field width here
3559 // makes no sense. Worth issuing a warning at some point.
3560 return true;
3561 }
3562
3563 // Consume the argument.
3564 unsigned argIndex = FS.getArgIndex();
3565 if (argIndex < NumDataArgs) {
3566 // The check to see if the argIndex is valid will come later.
3567 // We set the bit here because we may exit early from this
3568 // function if we encounter some other error.
3569 CoveredArgs.set(argIndex);
3570 }
3571
Ted Kremenek4407ea42010-07-20 20:04:47 +00003572 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003573 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003574 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3575 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003576 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003577 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003578 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003579 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3580 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003581
Jordan Rose92303592012-09-08 04:00:03 +00003582 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3583 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3584
Ted Kremenek02087932010-07-16 02:11:22 +00003585 // The remaining checks depend on the data arguments.
3586 if (HasVAListArg)
3587 return true;
3588
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003589 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003590 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003591
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003592 // Check that the argument type matches the format specifier.
3593 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003594 if (!Ex)
3595 return true;
3596
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003597 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3598 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003599 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003600 bool success = fixedFS.fixType(Ex->getType(),
3601 Ex->IgnoreImpCasts()->getType(),
3602 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003603
3604 if (success) {
3605 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003606 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003607 llvm::raw_svector_ostream os(buf);
3608 fixedFS.toString(os);
3609
3610 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003611 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3612 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003613 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003614 Ex->getLocStart(),
3615 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003616 getSpecifierRange(startSpecifier, specifierLen),
3617 FixItHint::CreateReplacement(
3618 getSpecifierRange(startSpecifier, specifierLen),
3619 os.str()));
3620 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003621 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003622 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3623 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003624 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003625 Ex->getLocStart(),
3626 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003627 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003628 }
3629 }
3630
Ted Kremenek02087932010-07-16 02:11:22 +00003631 return true;
3632}
3633
3634void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003635 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003636 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003637 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003638 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003639 bool inFunctionCall, VariadicCallType CallType,
3640 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003641
Ted Kremenekab278de2010-01-28 23:39:18 +00003642 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003643 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003644 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003645 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3647 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003648 return;
3649 }
Ted Kremenek02087932010-07-16 02:11:22 +00003650
Ted Kremenekab278de2010-01-28 23:39:18 +00003651 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003652 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003653 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003654 // Account for cases where the string literal is truncated in a declaration.
3655 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3656 assert(T && "String literal not of constant array type!");
3657 size_t TypeSize = T->getSize().getZExtValue();
3658 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003659 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003660
3661 // Emit a warning if the string literal is truncated and does not contain an
3662 // embedded null character.
3663 if (TypeSize <= StrRef.size() &&
3664 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3665 CheckFormatHandler::EmitFormatDiagnostic(
3666 *this, inFunctionCall, Args[format_idx],
3667 PDiag(diag::warn_printf_format_string_not_null_terminated),
3668 FExpr->getLocStart(),
3669 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3670 return;
3671 }
3672
Ted Kremenekab278de2010-01-28 23:39:18 +00003673 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003674 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003675 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003676 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003677 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3678 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003679 return;
3680 }
Ted Kremenek02087932010-07-16 02:11:22 +00003681
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003682 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003683 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003684 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003685 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003686 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003687
Hans Wennborg23926bd2011-12-15 10:25:47 +00003688 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003689 getLangOpts(),
3690 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003691 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003692 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003693 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003694 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003695 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003696
Hans Wennborg23926bd2011-12-15 10:25:47 +00003697 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003698 getLangOpts(),
3699 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003700 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003701 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003702}
3703
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003704//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3705
3706// Returns the related absolute value function that is larger, of 0 if one
3707// does not exist.
3708static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3709 switch (AbsFunction) {
3710 default:
3711 return 0;
3712
3713 case Builtin::BI__builtin_abs:
3714 return Builtin::BI__builtin_labs;
3715 case Builtin::BI__builtin_labs:
3716 return Builtin::BI__builtin_llabs;
3717 case Builtin::BI__builtin_llabs:
3718 return 0;
3719
3720 case Builtin::BI__builtin_fabsf:
3721 return Builtin::BI__builtin_fabs;
3722 case Builtin::BI__builtin_fabs:
3723 return Builtin::BI__builtin_fabsl;
3724 case Builtin::BI__builtin_fabsl:
3725 return 0;
3726
3727 case Builtin::BI__builtin_cabsf:
3728 return Builtin::BI__builtin_cabs;
3729 case Builtin::BI__builtin_cabs:
3730 return Builtin::BI__builtin_cabsl;
3731 case Builtin::BI__builtin_cabsl:
3732 return 0;
3733
3734 case Builtin::BIabs:
3735 return Builtin::BIlabs;
3736 case Builtin::BIlabs:
3737 return Builtin::BIllabs;
3738 case Builtin::BIllabs:
3739 return 0;
3740
3741 case Builtin::BIfabsf:
3742 return Builtin::BIfabs;
3743 case Builtin::BIfabs:
3744 return Builtin::BIfabsl;
3745 case Builtin::BIfabsl:
3746 return 0;
3747
3748 case Builtin::BIcabsf:
3749 return Builtin::BIcabs;
3750 case Builtin::BIcabs:
3751 return Builtin::BIcabsl;
3752 case Builtin::BIcabsl:
3753 return 0;
3754 }
3755}
3756
3757// Returns the argument type of the absolute value function.
3758static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3759 unsigned AbsType) {
3760 if (AbsType == 0)
3761 return QualType();
3762
3763 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3764 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3765 if (Error != ASTContext::GE_None)
3766 return QualType();
3767
3768 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3769 if (!FT)
3770 return QualType();
3771
3772 if (FT->getNumParams() != 1)
3773 return QualType();
3774
3775 return FT->getParamType(0);
3776}
3777
3778// Returns the best absolute value function, or zero, based on type and
3779// current absolute value function.
3780static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3781 unsigned AbsFunctionKind) {
3782 unsigned BestKind = 0;
3783 uint64_t ArgSize = Context.getTypeSize(ArgType);
3784 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3785 Kind = getLargerAbsoluteValueFunction(Kind)) {
3786 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3787 if (Context.getTypeSize(ParamType) >= ArgSize) {
3788 if (BestKind == 0)
3789 BestKind = Kind;
3790 else if (Context.hasSameType(ParamType, ArgType)) {
3791 BestKind = Kind;
3792 break;
3793 }
3794 }
3795 }
3796 return BestKind;
3797}
3798
3799enum AbsoluteValueKind {
3800 AVK_Integer,
3801 AVK_Floating,
3802 AVK_Complex
3803};
3804
3805static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3806 if (T->isIntegralOrEnumerationType())
3807 return AVK_Integer;
3808 if (T->isRealFloatingType())
3809 return AVK_Floating;
3810 if (T->isAnyComplexType())
3811 return AVK_Complex;
3812
3813 llvm_unreachable("Type not integer, floating, or complex");
3814}
3815
3816// Changes the absolute value function to a different type. Preserves whether
3817// the function is a builtin.
3818static unsigned changeAbsFunction(unsigned AbsKind,
3819 AbsoluteValueKind ValueKind) {
3820 switch (ValueKind) {
3821 case AVK_Integer:
3822 switch (AbsKind) {
3823 default:
3824 return 0;
3825 case Builtin::BI__builtin_fabsf:
3826 case Builtin::BI__builtin_fabs:
3827 case Builtin::BI__builtin_fabsl:
3828 case Builtin::BI__builtin_cabsf:
3829 case Builtin::BI__builtin_cabs:
3830 case Builtin::BI__builtin_cabsl:
3831 return Builtin::BI__builtin_abs;
3832 case Builtin::BIfabsf:
3833 case Builtin::BIfabs:
3834 case Builtin::BIfabsl:
3835 case Builtin::BIcabsf:
3836 case Builtin::BIcabs:
3837 case Builtin::BIcabsl:
3838 return Builtin::BIabs;
3839 }
3840 case AVK_Floating:
3841 switch (AbsKind) {
3842 default:
3843 return 0;
3844 case Builtin::BI__builtin_abs:
3845 case Builtin::BI__builtin_labs:
3846 case Builtin::BI__builtin_llabs:
3847 case Builtin::BI__builtin_cabsf:
3848 case Builtin::BI__builtin_cabs:
3849 case Builtin::BI__builtin_cabsl:
3850 return Builtin::BI__builtin_fabsf;
3851 case Builtin::BIabs:
3852 case Builtin::BIlabs:
3853 case Builtin::BIllabs:
3854 case Builtin::BIcabsf:
3855 case Builtin::BIcabs:
3856 case Builtin::BIcabsl:
3857 return Builtin::BIfabsf;
3858 }
3859 case AVK_Complex:
3860 switch (AbsKind) {
3861 default:
3862 return 0;
3863 case Builtin::BI__builtin_abs:
3864 case Builtin::BI__builtin_labs:
3865 case Builtin::BI__builtin_llabs:
3866 case Builtin::BI__builtin_fabsf:
3867 case Builtin::BI__builtin_fabs:
3868 case Builtin::BI__builtin_fabsl:
3869 return Builtin::BI__builtin_cabsf;
3870 case Builtin::BIabs:
3871 case Builtin::BIlabs:
3872 case Builtin::BIllabs:
3873 case Builtin::BIfabsf:
3874 case Builtin::BIfabs:
3875 case Builtin::BIfabsl:
3876 return Builtin::BIcabsf;
3877 }
3878 }
3879 llvm_unreachable("Unable to convert function");
3880}
3881
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003882static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003883 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3884 if (!FnInfo)
3885 return 0;
3886
3887 switch (FDecl->getBuiltinID()) {
3888 default:
3889 return 0;
3890 case Builtin::BI__builtin_abs:
3891 case Builtin::BI__builtin_fabs:
3892 case Builtin::BI__builtin_fabsf:
3893 case Builtin::BI__builtin_fabsl:
3894 case Builtin::BI__builtin_labs:
3895 case Builtin::BI__builtin_llabs:
3896 case Builtin::BI__builtin_cabs:
3897 case Builtin::BI__builtin_cabsf:
3898 case Builtin::BI__builtin_cabsl:
3899 case Builtin::BIabs:
3900 case Builtin::BIlabs:
3901 case Builtin::BIllabs:
3902 case Builtin::BIfabs:
3903 case Builtin::BIfabsf:
3904 case Builtin::BIfabsl:
3905 case Builtin::BIcabs:
3906 case Builtin::BIcabsf:
3907 case Builtin::BIcabsl:
3908 return FDecl->getBuiltinID();
3909 }
3910 llvm_unreachable("Unknown Builtin type");
3911}
3912
3913// If the replacement is valid, emit a note with replacement function.
3914// Additionally, suggest including the proper header if not already included.
3915static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003916 unsigned AbsKind, QualType ArgType) {
3917 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003918 const char *HeaderName = nullptr;
3919 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003920 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3921 FunctionName = "std::abs";
3922 if (ArgType->isIntegralOrEnumerationType()) {
3923 HeaderName = "cstdlib";
3924 } else if (ArgType->isRealFloatingType()) {
3925 HeaderName = "cmath";
3926 } else {
3927 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003928 }
Richard Trieubeffb832014-04-15 23:47:53 +00003929
3930 // Lookup all std::abs
3931 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003932 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003933 R.suppressDiagnostics();
3934 S.LookupQualifiedName(R, Std);
3935
3936 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003937 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003938 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3939 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3940 } else {
3941 FDecl = dyn_cast<FunctionDecl>(I);
3942 }
3943 if (!FDecl)
3944 continue;
3945
3946 // Found std::abs(), check that they are the right ones.
3947 if (FDecl->getNumParams() != 1)
3948 continue;
3949
3950 // Check that the parameter type can handle the argument.
3951 QualType ParamType = FDecl->getParamDecl(0)->getType();
3952 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3953 S.Context.getTypeSize(ArgType) <=
3954 S.Context.getTypeSize(ParamType)) {
3955 // Found a function, don't need the header hint.
3956 EmitHeaderHint = false;
3957 break;
3958 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003959 }
Richard Trieubeffb832014-04-15 23:47:53 +00003960 }
3961 } else {
3962 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3963 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3964
3965 if (HeaderName) {
3966 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3967 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3968 R.suppressDiagnostics();
3969 S.LookupName(R, S.getCurScope());
3970
3971 if (R.isSingleResult()) {
3972 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3973 if (FD && FD->getBuiltinID() == AbsKind) {
3974 EmitHeaderHint = false;
3975 } else {
3976 return;
3977 }
3978 } else if (!R.empty()) {
3979 return;
3980 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003981 }
3982 }
3983
3984 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003985 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003986
Richard Trieubeffb832014-04-15 23:47:53 +00003987 if (!HeaderName)
3988 return;
3989
3990 if (!EmitHeaderHint)
3991 return;
3992
Alp Toker5d96e0a2014-07-11 20:53:51 +00003993 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3994 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003995}
3996
3997static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3998 if (!FDecl)
3999 return false;
4000
4001 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4002 return false;
4003
4004 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4005
4006 while (ND && ND->isInlineNamespace()) {
4007 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004008 }
Richard Trieubeffb832014-04-15 23:47:53 +00004009
4010 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4011 return false;
4012
4013 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4014 return false;
4015
4016 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004017}
4018
4019// Warn when using the wrong abs() function.
4020void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4021 const FunctionDecl *FDecl,
4022 IdentifierInfo *FnInfo) {
4023 if (Call->getNumArgs() != 1)
4024 return;
4025
4026 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004027 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4028 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004029 return;
4030
4031 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4032 QualType ParamType = Call->getArg(0)->getType();
4033
Alp Toker5d96e0a2014-07-11 20:53:51 +00004034 // Unsigned types cannot be negative. Suggest removing the absolute value
4035 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004036 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004037 const char *FunctionName =
4038 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004039 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4040 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004041 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004042 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4043 return;
4044 }
4045
Richard Trieubeffb832014-04-15 23:47:53 +00004046 // std::abs has overloads which prevent most of the absolute value problems
4047 // from occurring.
4048 if (IsStdAbs)
4049 return;
4050
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004051 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4052 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4053
4054 // The argument and parameter are the same kind. Check if they are the right
4055 // size.
4056 if (ArgValueKind == ParamValueKind) {
4057 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4058 return;
4059
4060 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4061 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4062 << FDecl << ArgType << ParamType;
4063
4064 if (NewAbsKind == 0)
4065 return;
4066
4067 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004068 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004069 return;
4070 }
4071
4072 // ArgValueKind != ParamValueKind
4073 // The wrong type of absolute value function was used. Attempt to find the
4074 // proper one.
4075 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4076 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4077 if (NewAbsKind == 0)
4078 return;
4079
4080 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4081 << FDecl << ParamValueKind << ArgValueKind;
4082
4083 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004084 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004085 return;
4086}
4087
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004088//===--- CHECK: Standard memory functions ---------------------------------===//
4089
Nico Weber0e6daef2013-12-26 23:38:39 +00004090/// \brief Takes the expression passed to the size_t parameter of functions
4091/// such as memcmp, strncat, etc and warns if it's a comparison.
4092///
4093/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4094static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4095 IdentifierInfo *FnName,
4096 SourceLocation FnLoc,
4097 SourceLocation RParenLoc) {
4098 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4099 if (!Size)
4100 return false;
4101
4102 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4103 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4104 return false;
4105
Nico Weber0e6daef2013-12-26 23:38:39 +00004106 SourceRange SizeRange = Size->getSourceRange();
4107 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4108 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004109 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004110 << FnName << FixItHint::CreateInsertion(
4111 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004112 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004113 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004114 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004115 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4116 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004117
4118 return true;
4119}
4120
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004121/// \brief Determine whether the given type is or contains a dynamic class type
4122/// (e.g., whether it has a vtable).
4123static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4124 bool &IsContained) {
4125 // Look through array types while ignoring qualifiers.
4126 const Type *Ty = T->getBaseElementTypeUnsafe();
4127 IsContained = false;
4128
4129 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4130 RD = RD ? RD->getDefinition() : nullptr;
4131 if (!RD)
4132 return nullptr;
4133
4134 if (RD->isDynamicClass())
4135 return RD;
4136
4137 // Check all the fields. If any bases were dynamic, the class is dynamic.
4138 // It's impossible for a class to transitively contain itself by value, so
4139 // infinite recursion is impossible.
4140 for (auto *FD : RD->fields()) {
4141 bool SubContained;
4142 if (const CXXRecordDecl *ContainedRD =
4143 getContainedDynamicClass(FD->getType(), SubContained)) {
4144 IsContained = true;
4145 return ContainedRD;
4146 }
4147 }
4148
4149 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004150}
4151
Chandler Carruth889ed862011-06-21 23:04:20 +00004152/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004153/// otherwise returns NULL.
4154static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004155 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004156 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4157 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4158 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004159
Craig Topperc3ec1492014-05-26 06:22:03 +00004160 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004161}
4162
Chandler Carruth889ed862011-06-21 23:04:20 +00004163/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004164static QualType getSizeOfArgType(const Expr* E) {
4165 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4166 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4167 if (SizeOf->getKind() == clang::UETT_SizeOf)
4168 return SizeOf->getTypeOfArgument();
4169
4170 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004171}
4172
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004173/// \brief Check for dangerous or invalid arguments to memset().
4174///
Chandler Carruthac687262011-06-03 06:23:57 +00004175/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004176/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4177/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004178///
4179/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004180void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004181 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004182 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004183 assert(BId != 0);
4184
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004185 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004186 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004187 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004188 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004189 return;
4190
Anna Zaks22122702012-01-17 00:37:07 +00004191 unsigned LastArg = (BId == Builtin::BImemset ||
4192 BId == Builtin::BIstrndup ? 1 : 2);
4193 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004194 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004195
Nico Weber0e6daef2013-12-26 23:38:39 +00004196 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4197 Call->getLocStart(), Call->getRParenLoc()))
4198 return;
4199
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004200 // We have special checking when the length is a sizeof expression.
4201 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4202 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4203 llvm::FoldingSetNodeID SizeOfArgID;
4204
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004205 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4206 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004207 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004208
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004209 QualType DestTy = Dest->getType();
4210 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4211 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004212
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004213 // Never warn about void type pointers. This can be used to suppress
4214 // false positives.
4215 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004216 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004217
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004218 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4219 // actually comparing the expressions for equality. Because computing the
4220 // expression IDs can be expensive, we only do this if the diagnostic is
4221 // enabled.
4222 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004223 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4224 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004225 // We only compute IDs for expressions if the warning is enabled, and
4226 // cache the sizeof arg's ID.
4227 if (SizeOfArgID == llvm::FoldingSetNodeID())
4228 SizeOfArg->Profile(SizeOfArgID, Context, true);
4229 llvm::FoldingSetNodeID DestID;
4230 Dest->Profile(DestID, Context, true);
4231 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004232 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4233 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004234 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004235 StringRef ReadableName = FnName->getName();
4236
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004237 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004238 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004239 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004240 if (!PointeeTy->isIncompleteType() &&
4241 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004242 ActionIdx = 2; // If the pointee's size is sizeof(char),
4243 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004244
4245 // If the function is defined as a builtin macro, do not show macro
4246 // expansion.
4247 SourceLocation SL = SizeOfArg->getExprLoc();
4248 SourceRange DSR = Dest->getSourceRange();
4249 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004250 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004251
4252 if (SM.isMacroArgExpansion(SL)) {
4253 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4254 SL = SM.getSpellingLoc(SL);
4255 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4256 SM.getSpellingLoc(DSR.getEnd()));
4257 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4258 SM.getSpellingLoc(SSR.getEnd()));
4259 }
4260
Anna Zaksd08d9152012-05-30 23:14:52 +00004261 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004262 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004263 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004264 << PointeeTy
4265 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004266 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004267 << SSR);
4268 DiagRuntimeBehavior(SL, SizeOfArg,
4269 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4270 << ActionIdx
4271 << SSR);
4272
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004273 break;
4274 }
4275 }
4276
4277 // Also check for cases where the sizeof argument is the exact same
4278 // type as the memory argument, and where it points to a user-defined
4279 // record type.
4280 if (SizeOfArgTy != QualType()) {
4281 if (PointeeTy->isRecordType() &&
4282 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4283 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4284 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4285 << FnName << SizeOfArgTy << ArgIdx
4286 << PointeeTy << Dest->getSourceRange()
4287 << LenExpr->getSourceRange());
4288 break;
4289 }
Nico Weberc5e73862011-06-14 16:14:58 +00004290 }
4291
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004292 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004293 bool IsContained;
4294 if (const CXXRecordDecl *ContainedRD =
4295 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004296
4297 unsigned OperationType = 0;
4298 // "overwritten" if we're warning about the destination for any call
4299 // but memcmp; otherwise a verb appropriate to the call.
4300 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4301 if (BId == Builtin::BImemcpy)
4302 OperationType = 1;
4303 else if(BId == Builtin::BImemmove)
4304 OperationType = 2;
4305 else if (BId == Builtin::BImemcmp)
4306 OperationType = 3;
4307 }
4308
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004309 DiagRuntimeBehavior(
4310 Dest->getExprLoc(), Dest,
4311 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004312 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004313 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004314 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004315 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4316 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004317 DiagRuntimeBehavior(
4318 Dest->getExprLoc(), Dest,
4319 PDiag(diag::warn_arc_object_memaccess)
4320 << ArgIdx << FnName << PointeeTy
4321 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004322 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004323 continue;
John McCall31168b02011-06-15 23:02:42 +00004324
4325 DiagRuntimeBehavior(
4326 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004327 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004328 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4329 break;
4330 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004331 }
4332}
4333
Ted Kremenek6865f772011-08-18 20:55:45 +00004334// A little helper routine: ignore addition and subtraction of integer literals.
4335// This intentionally does not ignore all integer constant expressions because
4336// we don't want to remove sizeof().
4337static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4338 Ex = Ex->IgnoreParenCasts();
4339
4340 for (;;) {
4341 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4342 if (!BO || !BO->isAdditiveOp())
4343 break;
4344
4345 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4346 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4347
4348 if (isa<IntegerLiteral>(RHS))
4349 Ex = LHS;
4350 else if (isa<IntegerLiteral>(LHS))
4351 Ex = RHS;
4352 else
4353 break;
4354 }
4355
4356 return Ex;
4357}
4358
Anna Zaks13b08572012-08-08 21:42:23 +00004359static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4360 ASTContext &Context) {
4361 // Only handle constant-sized or VLAs, but not flexible members.
4362 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4363 // Only issue the FIXIT for arrays of size > 1.
4364 if (CAT->getSize().getSExtValue() <= 1)
4365 return false;
4366 } else if (!Ty->isVariableArrayType()) {
4367 return false;
4368 }
4369 return true;
4370}
4371
Ted Kremenek6865f772011-08-18 20:55:45 +00004372// Warn if the user has made the 'size' argument to strlcpy or strlcat
4373// be the size of the source, instead of the destination.
4374void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4375 IdentifierInfo *FnName) {
4376
4377 // Don't crash if the user has the wrong number of arguments
4378 if (Call->getNumArgs() != 3)
4379 return;
4380
4381 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4382 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004383 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004384
4385 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4386 Call->getLocStart(), Call->getRParenLoc()))
4387 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004388
4389 // Look for 'strlcpy(dst, x, sizeof(x))'
4390 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4391 CompareWithSrc = Ex;
4392 else {
4393 // Look for 'strlcpy(dst, x, strlen(x))'
4394 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004395 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4396 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004397 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4398 }
4399 }
4400
4401 if (!CompareWithSrc)
4402 return;
4403
4404 // Determine if the argument to sizeof/strlen is equal to the source
4405 // argument. In principle there's all kinds of things you could do
4406 // here, for instance creating an == expression and evaluating it with
4407 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4408 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4409 if (!SrcArgDRE)
4410 return;
4411
4412 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4413 if (!CompareWithSrcDRE ||
4414 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4415 return;
4416
4417 const Expr *OriginalSizeArg = Call->getArg(2);
4418 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4419 << OriginalSizeArg->getSourceRange() << FnName;
4420
4421 // Output a FIXIT hint if the destination is an array (rather than a
4422 // pointer to an array). This could be enhanced to handle some
4423 // pointers if we know the actual size, like if DstArg is 'array+2'
4424 // we could say 'sizeof(array)-2'.
4425 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004426 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004427 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004428
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004429 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004430 llvm::raw_svector_ostream OS(sizeString);
4431 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004432 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004433 OS << ")";
4434
4435 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4436 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4437 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004438}
4439
Anna Zaks314cd092012-02-01 19:08:57 +00004440/// Check if two expressions refer to the same declaration.
4441static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4442 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4443 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4444 return D1->getDecl() == D2->getDecl();
4445 return false;
4446}
4447
4448static const Expr *getStrlenExprArg(const Expr *E) {
4449 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4450 const FunctionDecl *FD = CE->getDirectCallee();
4451 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004452 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004453 return CE->getArg(0)->IgnoreParenCasts();
4454 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004455 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004456}
4457
4458// Warn on anti-patterns as the 'size' argument to strncat.
4459// The correct size argument should look like following:
4460// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4461void Sema::CheckStrncatArguments(const CallExpr *CE,
4462 IdentifierInfo *FnName) {
4463 // Don't crash if the user has the wrong number of arguments.
4464 if (CE->getNumArgs() < 3)
4465 return;
4466 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4467 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4468 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4469
Nico Weber0e6daef2013-12-26 23:38:39 +00004470 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4471 CE->getRParenLoc()))
4472 return;
4473
Anna Zaks314cd092012-02-01 19:08:57 +00004474 // Identify common expressions, which are wrongly used as the size argument
4475 // to strncat and may lead to buffer overflows.
4476 unsigned PatternType = 0;
4477 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4478 // - sizeof(dst)
4479 if (referToTheSameDecl(SizeOfArg, DstArg))
4480 PatternType = 1;
4481 // - sizeof(src)
4482 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4483 PatternType = 2;
4484 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4485 if (BE->getOpcode() == BO_Sub) {
4486 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4487 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4488 // - sizeof(dst) - strlen(dst)
4489 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4490 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4491 PatternType = 1;
4492 // - sizeof(src) - (anything)
4493 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4494 PatternType = 2;
4495 }
4496 }
4497
4498 if (PatternType == 0)
4499 return;
4500
Anna Zaks5069aa32012-02-03 01:27:37 +00004501 // Generate the diagnostic.
4502 SourceLocation SL = LenArg->getLocStart();
4503 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004504 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004505
4506 // If the function is defined as a builtin macro, do not show macro expansion.
4507 if (SM.isMacroArgExpansion(SL)) {
4508 SL = SM.getSpellingLoc(SL);
4509 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4510 SM.getSpellingLoc(SR.getEnd()));
4511 }
4512
Anna Zaks13b08572012-08-08 21:42:23 +00004513 // Check if the destination is an array (rather than a pointer to an array).
4514 QualType DstTy = DstArg->getType();
4515 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4516 Context);
4517 if (!isKnownSizeArray) {
4518 if (PatternType == 1)
4519 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4520 else
4521 Diag(SL, diag::warn_strncat_src_size) << SR;
4522 return;
4523 }
4524
Anna Zaks314cd092012-02-01 19:08:57 +00004525 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004526 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004527 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004528 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004529
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004530 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004531 llvm::raw_svector_ostream OS(sizeString);
4532 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004534 OS << ") - ";
4535 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004536 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004537 OS << ") - 1";
4538
Anna Zaks5069aa32012-02-03 01:27:37 +00004539 Diag(SL, diag::note_strncat_wrong_size)
4540 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004541}
4542
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004543//===--- CHECK: Return Address of Stack Variable --------------------------===//
4544
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004545static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4546 Decl *ParentDecl);
4547static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4548 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004549
4550/// CheckReturnStackAddr - Check if a return statement returns the address
4551/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004552static void
4553CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4554 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004555
Craig Topperc3ec1492014-05-26 06:22:03 +00004556 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004557 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004558
4559 // Perform checking for returned stack addresses, local blocks,
4560 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004561 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004562 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004563 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004564 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004565 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004566 }
4567
Craig Topperc3ec1492014-05-26 06:22:03 +00004568 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004569 return; // Nothing suspicious was found.
4570
4571 SourceLocation diagLoc;
4572 SourceRange diagRange;
4573 if (refVars.empty()) {
4574 diagLoc = stackE->getLocStart();
4575 diagRange = stackE->getSourceRange();
4576 } else {
4577 // We followed through a reference variable. 'stackE' contains the
4578 // problematic expression but we will warn at the return statement pointing
4579 // at the reference variable. We will later display the "trail" of
4580 // reference variables using notes.
4581 diagLoc = refVars[0]->getLocStart();
4582 diagRange = refVars[0]->getSourceRange();
4583 }
4584
4585 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004586 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004587 : diag::warn_ret_stack_addr)
4588 << DR->getDecl()->getDeclName() << diagRange;
4589 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004590 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004591 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004592 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004593 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004594 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4595 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004596 << diagRange;
4597 }
4598
4599 // Display the "trail" of reference variables that we followed until we
4600 // found the problematic expression using notes.
4601 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4602 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4603 // If this var binds to another reference var, show the range of the next
4604 // var, otherwise the var binds to the problematic expression, in which case
4605 // show the range of the expression.
4606 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4607 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004608 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4609 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004610 }
4611}
4612
4613/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4614/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004615/// to a location on the stack, a local block, an address of a label, or a
4616/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004617/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004618/// encounter a subexpression that (1) clearly does not lead to one of the
4619/// above problematic expressions (2) is something we cannot determine leads to
4620/// a problematic expression based on such local checking.
4621///
4622/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4623/// the expression that they point to. Such variables are added to the
4624/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004625///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004626/// EvalAddr processes expressions that are pointers that are used as
4627/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004628/// At the base case of the recursion is a check for the above problematic
4629/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004630///
4631/// This implementation handles:
4632///
4633/// * pointer-to-pointer casts
4634/// * implicit conversions from array references to pointers
4635/// * taking the address of fields
4636/// * arbitrary interplay between "&" and "*" operators
4637/// * pointer arithmetic from an address of a stack variable
4638/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004639static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4640 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004641 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004642 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004643
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004644 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004645 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004646 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004647 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004648 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004649
Peter Collingbourne91147592011-04-15 00:35:48 +00004650 E = E->IgnoreParens();
4651
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004652 // Our "symbolic interpreter" is just a dispatch off the currently
4653 // viewed AST node. We then recursively traverse the AST by calling
4654 // EvalAddr and EvalVal appropriately.
4655 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004656 case Stmt::DeclRefExprClass: {
4657 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4658
Richard Smith40f08eb2014-01-30 22:05:38 +00004659 // If we leave the immediate function, the lifetime isn't about to end.
4660 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004661 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004662
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004663 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4664 // If this is a reference variable, follow through to the expression that
4665 // it points to.
4666 if (V->hasLocalStorage() &&
4667 V->getType()->isReferenceType() && V->hasInit()) {
4668 // Add the reference variable to the "trail".
4669 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004670 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004671 }
4672
Craig Topperc3ec1492014-05-26 06:22:03 +00004673 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004674 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004675
Chris Lattner934edb22007-12-28 05:31:15 +00004676 case Stmt::UnaryOperatorClass: {
4677 // The only unary operator that make sense to handle here
4678 // is AddrOf. All others don't make sense as pointers.
4679 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004680
John McCalle3027922010-08-25 11:45:40 +00004681 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004682 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004683 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004684 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
Chris Lattner934edb22007-12-28 05:31:15 +00004687 case Stmt::BinaryOperatorClass: {
4688 // Handle pointer arithmetic. All other binary operators are not valid
4689 // in this context.
4690 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004691 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004692
John McCalle3027922010-08-25 11:45:40 +00004693 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004694 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004695
Chris Lattner934edb22007-12-28 05:31:15 +00004696 Expr *Base = B->getLHS();
4697
4698 // Determine which argument is the real pointer base. It could be
4699 // the RHS argument instead of the LHS.
4700 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004701
Chris Lattner934edb22007-12-28 05:31:15 +00004702 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004703 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004704 }
Steve Naroff2752a172008-09-10 19:17:48 +00004705
Chris Lattner934edb22007-12-28 05:31:15 +00004706 // For conditional operators we need to see if either the LHS or RHS are
4707 // valid DeclRefExpr*s. If one of them is valid, we return it.
4708 case Stmt::ConditionalOperatorClass: {
4709 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004710
Chris Lattner934edb22007-12-28 05:31:15 +00004711 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004712 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4713 if (Expr *LHSExpr = C->getLHS()) {
4714 // In C++, we can have a throw-expression, which has 'void' type.
4715 if (!LHSExpr->getType()->isVoidType())
4716 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004717 return LHS;
4718 }
Chris Lattner934edb22007-12-28 05:31:15 +00004719
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004720 // In C++, we can have a throw-expression, which has 'void' type.
4721 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004722 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004723
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004724 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004725 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004726
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004727 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004728 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004729 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004730 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004731
4732 case Stmt::AddrLabelExprClass:
4733 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004734
John McCall28fc7092011-11-10 05:35:25 +00004735 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004736 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4737 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004738
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004739 // For casts, we need to handle conversions from arrays to
4740 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004741 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004742 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004743 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004744 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004745 case Stmt::CXXStaticCastExprClass:
4746 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004747 case Stmt::CXXConstCastExprClass:
4748 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004749 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4750 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004751 case CK_LValueToRValue:
4752 case CK_NoOp:
4753 case CK_BaseToDerived:
4754 case CK_DerivedToBase:
4755 case CK_UncheckedDerivedToBase:
4756 case CK_Dynamic:
4757 case CK_CPointerToObjCPointerCast:
4758 case CK_BlockPointerToObjCPointerCast:
4759 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004760 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004761
4762 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004763 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004764
Richard Trieudadefde2014-07-02 04:39:38 +00004765 case CK_BitCast:
4766 if (SubExpr->getType()->isAnyPointerType() ||
4767 SubExpr->getType()->isBlockPointerType() ||
4768 SubExpr->getType()->isObjCQualifiedIdType())
4769 return EvalAddr(SubExpr, refVars, ParentDecl);
4770 else
4771 return nullptr;
4772
Eli Friedman8195ad72012-02-23 23:04:32 +00004773 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004774 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004775 }
Chris Lattner934edb22007-12-28 05:31:15 +00004776 }
Mike Stump11289f42009-09-09 15:08:12 +00004777
Douglas Gregorfe314812011-06-21 17:03:29 +00004778 case Stmt::MaterializeTemporaryExprClass:
4779 if (Expr *Result = EvalAddr(
4780 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004781 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004782 return Result;
4783
4784 return E;
4785
Chris Lattner934edb22007-12-28 05:31:15 +00004786 // Everything else: we simply don't reason about them.
4787 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004788 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004789 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004790}
Mike Stump11289f42009-09-09 15:08:12 +00004791
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004792
4793/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4794/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004795static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4796 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004797do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004798 // We should only be called for evaluating non-pointer expressions, or
4799 // expressions with a pointer type that are not used as references but instead
4800 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004801
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004802 // Our "symbolic interpreter" is just a dispatch off the currently
4803 // viewed AST node. We then recursively traverse the AST by calling
4804 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004805
4806 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004807 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004808 case Stmt::ImplicitCastExprClass: {
4809 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004810 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004811 E = IE->getSubExpr();
4812 continue;
4813 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004814 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004815 }
4816
John McCall28fc7092011-11-10 05:35:25 +00004817 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004818 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004819
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004820 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004821 // When we hit a DeclRefExpr we are looking at code that refers to a
4822 // variable's name. If it's not a reference variable we check if it has
4823 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004824 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004825
Richard Smith40f08eb2014-01-30 22:05:38 +00004826 // If we leave the immediate function, the lifetime isn't about to end.
4827 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004828 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004829
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004830 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4831 // Check if it refers to itself, e.g. "int& i = i;".
4832 if (V == ParentDecl)
4833 return DR;
4834
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004835 if (V->hasLocalStorage()) {
4836 if (!V->getType()->isReferenceType())
4837 return DR;
4838
4839 // Reference variable, follow through to the expression that
4840 // it points to.
4841 if (V->hasInit()) {
4842 // Add the reference variable to the "trail".
4843 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004844 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004845 }
4846 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848
Craig Topperc3ec1492014-05-26 06:22:03 +00004849 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004852 case Stmt::UnaryOperatorClass: {
4853 // The only unary operator that make sense to handle here
4854 // is Deref. All others don't resolve to a "name." This includes
4855 // handling all sorts of rvalues passed to a unary operator.
4856 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004857
John McCalle3027922010-08-25 11:45:40 +00004858 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004859 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004860
Craig Topperc3ec1492014-05-26 06:22:03 +00004861 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004862 }
Mike Stump11289f42009-09-09 15:08:12 +00004863
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004864 case Stmt::ArraySubscriptExprClass: {
4865 // Array subscripts are potential references to data on the stack. We
4866 // retrieve the DeclRefExpr* for the array variable if it indeed
4867 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004868 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004869 }
Mike Stump11289f42009-09-09 15:08:12 +00004870
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004871 case Stmt::ConditionalOperatorClass: {
4872 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004873 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004874 ConditionalOperator *C = cast<ConditionalOperator>(E);
4875
Anders Carlsson801c5c72007-11-30 19:04:31 +00004876 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004877 if (Expr *LHSExpr = C->getLHS()) {
4878 // In C++, we can have a throw-expression, which has 'void' type.
4879 if (!LHSExpr->getType()->isVoidType())
4880 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4881 return LHS;
4882 }
4883
4884 // In C++, we can have a throw-expression, which has 'void' type.
4885 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004886 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004887
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004888 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004889 }
Mike Stump11289f42009-09-09 15:08:12 +00004890
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004891 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004892 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004893 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004894
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004895 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004896 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004897 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004898
4899 // Check whether the member type is itself a reference, in which case
4900 // we're not going to refer to the member, but to what the member refers to.
4901 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004902 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004903
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004904 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004905 }
Mike Stump11289f42009-09-09 15:08:12 +00004906
Douglas Gregorfe314812011-06-21 17:03:29 +00004907 case Stmt::MaterializeTemporaryExprClass:
4908 if (Expr *Result = EvalVal(
4909 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004910 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004911 return Result;
4912
4913 return E;
4914
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004915 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004916 // Check that we don't return or take the address of a reference to a
4917 // temporary. This is only useful in C++.
4918 if (!E->isTypeDependent() && E->isRValue())
4919 return E;
4920
4921 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004922 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004923 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004924} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004925}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004926
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004927void
4928Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4929 SourceLocation ReturnLoc,
4930 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004931 const AttrVec *Attrs,
4932 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004933 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4934
4935 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004936 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4937 CheckNonNullExpr(*this, RetValExp))
4938 Diag(ReturnLoc, diag::warn_null_ret)
4939 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004940
4941 // C++11 [basic.stc.dynamic.allocation]p4:
4942 // If an allocation function declared with a non-throwing
4943 // exception-specification fails to allocate storage, it shall return
4944 // a null pointer. Any other allocation function that fails to allocate
4945 // storage shall indicate failure only by throwing an exception [...]
4946 if (FD) {
4947 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4948 if (Op == OO_New || Op == OO_Array_New) {
4949 const FunctionProtoType *Proto
4950 = FD->getType()->castAs<FunctionProtoType>();
4951 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4952 CheckNonNullExpr(*this, RetValExp))
4953 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4954 << FD << getLangOpts().CPlusPlus11;
4955 }
4956 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004957}
4958
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004959//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4960
4961/// Check for comparisons of floating point operands using != and ==.
4962/// Issue a warning if these are no self-comparisons, as they are not likely
4963/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004964void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004965 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4966 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004967
4968 // Special case: check for x == x (which is OK).
4969 // Do not emit warnings for such cases.
4970 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4971 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4972 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004973 return;
Mike Stump11289f42009-09-09 15:08:12 +00004974
4975
Ted Kremenekeda40e22007-11-29 00:59:04 +00004976 // Special case: check for comparisons against literals that can be exactly
4977 // represented by APFloat. In such cases, do not emit a warning. This
4978 // is a heuristic: often comparison against such literals are used to
4979 // detect if a value in a variable has not changed. This clearly can
4980 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004981 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4982 if (FLL->isExact())
4983 return;
4984 } else
4985 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4986 if (FLR->isExact())
4987 return;
Mike Stump11289f42009-09-09 15:08:12 +00004988
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004989 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004990 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004991 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004992 return;
Mike Stump11289f42009-09-09 15:08:12 +00004993
David Blaikie1f4ff152012-07-16 20:47:22 +00004994 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004995 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004996 return;
Mike Stump11289f42009-09-09 15:08:12 +00004997
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004998 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004999 Diag(Loc, diag::warn_floatingpoint_eq)
5000 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005001}
John McCallca01b222010-01-04 23:21:16 +00005002
John McCall70aa5392010-01-06 05:24:50 +00005003//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5004//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005005
John McCall70aa5392010-01-06 05:24:50 +00005006namespace {
John McCallca01b222010-01-04 23:21:16 +00005007
John McCall70aa5392010-01-06 05:24:50 +00005008/// Structure recording the 'active' range of an integer-valued
5009/// expression.
5010struct IntRange {
5011 /// The number of bits active in the int.
5012 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005013
John McCall70aa5392010-01-06 05:24:50 +00005014 /// True if the int is known not to have negative values.
5015 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005016
John McCall70aa5392010-01-06 05:24:50 +00005017 IntRange(unsigned Width, bool NonNegative)
5018 : Width(Width), NonNegative(NonNegative)
5019 {}
John McCallca01b222010-01-04 23:21:16 +00005020
John McCall817d4af2010-11-10 23:38:19 +00005021 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005022 static IntRange forBoolType() {
5023 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005024 }
5025
John McCall817d4af2010-11-10 23:38:19 +00005026 /// Returns the range of an opaque value of the given integral type.
5027 static IntRange forValueOfType(ASTContext &C, QualType T) {
5028 return forValueOfCanonicalType(C,
5029 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005030 }
5031
John McCall817d4af2010-11-10 23:38:19 +00005032 /// Returns the range of an opaque value of a canonical integral type.
5033 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005034 assert(T->isCanonicalUnqualified());
5035
5036 if (const VectorType *VT = dyn_cast<VectorType>(T))
5037 T = VT->getElementType().getTypePtr();
5038 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5039 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005040 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5041 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005042
David Majnemer6a426652013-06-07 22:07:20 +00005043 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005044 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005045 EnumDecl *Enum = ET->getDecl();
5046 if (!Enum->isCompleteDefinition())
5047 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005048
David Majnemer6a426652013-06-07 22:07:20 +00005049 unsigned NumPositive = Enum->getNumPositiveBits();
5050 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005051
David Majnemer6a426652013-06-07 22:07:20 +00005052 if (NumNegative == 0)
5053 return IntRange(NumPositive, true/*NonNegative*/);
5054 else
5055 return IntRange(std::max(NumPositive + 1, NumNegative),
5056 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005057 }
John McCall70aa5392010-01-06 05:24:50 +00005058
5059 const BuiltinType *BT = cast<BuiltinType>(T);
5060 assert(BT->isInteger());
5061
5062 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5063 }
5064
John McCall817d4af2010-11-10 23:38:19 +00005065 /// Returns the "target" range of a canonical integral type, i.e.
5066 /// the range of values expressible in the type.
5067 ///
5068 /// This matches forValueOfCanonicalType except that enums have the
5069 /// full range of their type, not the range of their enumerators.
5070 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5071 assert(T->isCanonicalUnqualified());
5072
5073 if (const VectorType *VT = dyn_cast<VectorType>(T))
5074 T = VT->getElementType().getTypePtr();
5075 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5076 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005077 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5078 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005079 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005080 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005081
5082 const BuiltinType *BT = cast<BuiltinType>(T);
5083 assert(BT->isInteger());
5084
5085 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5086 }
5087
5088 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005089 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005090 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005091 L.NonNegative && R.NonNegative);
5092 }
5093
John McCall817d4af2010-11-10 23:38:19 +00005094 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005095 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005096 return IntRange(std::min(L.Width, R.Width),
5097 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005098 }
5099};
5100
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005101static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5102 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005103 if (value.isSigned() && value.isNegative())
5104 return IntRange(value.getMinSignedBits(), false);
5105
5106 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005107 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005108
5109 // isNonNegative() just checks the sign bit without considering
5110 // signedness.
5111 return IntRange(value.getActiveBits(), true);
5112}
5113
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005114static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5115 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005116 if (result.isInt())
5117 return GetValueRange(C, result.getInt(), MaxWidth);
5118
5119 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005120 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5121 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5122 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5123 R = IntRange::join(R, El);
5124 }
John McCall70aa5392010-01-06 05:24:50 +00005125 return R;
5126 }
5127
5128 if (result.isComplexInt()) {
5129 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5130 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5131 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005132 }
5133
5134 // This can happen with lossless casts to intptr_t of "based" lvalues.
5135 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005136 // FIXME: The only reason we need to pass the type in here is to get
5137 // the sign right on this one case. It would be nice if APValue
5138 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005139 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005140 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005141}
John McCall70aa5392010-01-06 05:24:50 +00005142
Eli Friedmane6d33952013-07-08 20:20:06 +00005143static QualType GetExprType(Expr *E) {
5144 QualType Ty = E->getType();
5145 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5146 Ty = AtomicRHS->getValueType();
5147 return Ty;
5148}
5149
John McCall70aa5392010-01-06 05:24:50 +00005150/// Pseudo-evaluate the given integer expression, estimating the
5151/// range of values it might take.
5152///
5153/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005154static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005155 E = E->IgnoreParens();
5156
5157 // Try a full evaluation first.
5158 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005159 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005160 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005161
5162 // I think we only want to look through implicit casts here; if the
5163 // user has an explicit widening cast, we should treat the value as
5164 // being of the new, wider type.
5165 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005166 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005167 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5168
Eli Friedmane6d33952013-07-08 20:20:06 +00005169 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005170
John McCalle3027922010-08-25 11:45:40 +00005171 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005172
John McCall70aa5392010-01-06 05:24:50 +00005173 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005174 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005175 return OutputTypeRange;
5176
5177 IntRange SubRange
5178 = GetExprRange(C, CE->getSubExpr(),
5179 std::min(MaxWidth, OutputTypeRange.Width));
5180
5181 // Bail out if the subexpr's range is as wide as the cast type.
5182 if (SubRange.Width >= OutputTypeRange.Width)
5183 return OutputTypeRange;
5184
5185 // Otherwise, we take the smaller width, and we're non-negative if
5186 // either the output type or the subexpr is.
5187 return IntRange(SubRange.Width,
5188 SubRange.NonNegative || OutputTypeRange.NonNegative);
5189 }
5190
5191 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5192 // If we can fold the condition, just take that operand.
5193 bool CondResult;
5194 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5195 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5196 : CO->getFalseExpr(),
5197 MaxWidth);
5198
5199 // Otherwise, conservatively merge.
5200 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5201 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5202 return IntRange::join(L, R);
5203 }
5204
5205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5206 switch (BO->getOpcode()) {
5207
5208 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005209 case BO_LAnd:
5210 case BO_LOr:
5211 case BO_LT:
5212 case BO_GT:
5213 case BO_LE:
5214 case BO_GE:
5215 case BO_EQ:
5216 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005217 return IntRange::forBoolType();
5218
John McCallc3688382011-07-13 06:35:24 +00005219 // The type of the assignments is the type of the LHS, so the RHS
5220 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005221 case BO_MulAssign:
5222 case BO_DivAssign:
5223 case BO_RemAssign:
5224 case BO_AddAssign:
5225 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005226 case BO_XorAssign:
5227 case BO_OrAssign:
5228 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005229 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005230
John McCallc3688382011-07-13 06:35:24 +00005231 // Simple assignments just pass through the RHS, which will have
5232 // been coerced to the LHS type.
5233 case BO_Assign:
5234 // TODO: bitfields?
5235 return GetExprRange(C, BO->getRHS(), MaxWidth);
5236
John McCall70aa5392010-01-06 05:24:50 +00005237 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005238 case BO_PtrMemD:
5239 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005240 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005241
John McCall2ce81ad2010-01-06 22:07:33 +00005242 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005243 case BO_And:
5244 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005245 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5246 GetExprRange(C, BO->getRHS(), MaxWidth));
5247
John McCall70aa5392010-01-06 05:24:50 +00005248 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005249 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005250 // ...except that we want to treat '1 << (blah)' as logically
5251 // positive. It's an important idiom.
5252 if (IntegerLiteral *I
5253 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5254 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005255 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005256 return IntRange(R.Width, /*NonNegative*/ true);
5257 }
5258 }
5259 // fallthrough
5260
John McCalle3027922010-08-25 11:45:40 +00005261 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005262 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005263
John McCall2ce81ad2010-01-06 22:07:33 +00005264 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005265 case BO_Shr:
5266 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005267 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5268
5269 // If the shift amount is a positive constant, drop the width by
5270 // that much.
5271 llvm::APSInt shift;
5272 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5273 shift.isNonNegative()) {
5274 unsigned zext = shift.getZExtValue();
5275 if (zext >= L.Width)
5276 L.Width = (L.NonNegative ? 0 : 1);
5277 else
5278 L.Width -= zext;
5279 }
5280
5281 return L;
5282 }
5283
5284 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005285 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005286 return GetExprRange(C, BO->getRHS(), MaxWidth);
5287
John McCall2ce81ad2010-01-06 22:07:33 +00005288 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005289 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005290 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005291 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005292 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005293
John McCall51431812011-07-14 22:39:48 +00005294 // The width of a division result is mostly determined by the size
5295 // of the LHS.
5296 case BO_Div: {
5297 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005298 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005299 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5300
5301 // If the divisor is constant, use that.
5302 llvm::APSInt divisor;
5303 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5304 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5305 if (log2 >= L.Width)
5306 L.Width = (L.NonNegative ? 0 : 1);
5307 else
5308 L.Width = std::min(L.Width - log2, MaxWidth);
5309 return L;
5310 }
5311
5312 // Otherwise, just use the LHS's width.
5313 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5314 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5315 }
5316
5317 // The result of a remainder can't be larger than the result of
5318 // either side.
5319 case BO_Rem: {
5320 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005321 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005322 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5323 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5324
5325 IntRange meet = IntRange::meet(L, R);
5326 meet.Width = std::min(meet.Width, MaxWidth);
5327 return meet;
5328 }
5329
5330 // The default behavior is okay for these.
5331 case BO_Mul:
5332 case BO_Add:
5333 case BO_Xor:
5334 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005335 break;
5336 }
5337
John McCall51431812011-07-14 22:39:48 +00005338 // The default case is to treat the operation as if it were closed
5339 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005340 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5341 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5342 return IntRange::join(L, R);
5343 }
5344
5345 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5346 switch (UO->getOpcode()) {
5347 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005348 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005349 return IntRange::forBoolType();
5350
5351 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005352 case UO_Deref:
5353 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005354 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005355
5356 default:
5357 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5358 }
5359 }
5360
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005361 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5362 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5363
John McCalld25db7e2013-05-06 21:39:12 +00005364 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005365 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005366 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005367
Eli Friedmane6d33952013-07-08 20:20:06 +00005368 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005369}
John McCall263a48b2010-01-04 23:31:57 +00005370
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005371static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005372 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005373}
5374
John McCall263a48b2010-01-04 23:31:57 +00005375/// Checks whether the given value, which currently has the given
5376/// source semantics, has the same value when coerced through the
5377/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005378static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5379 const llvm::fltSemantics &Src,
5380 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005381 llvm::APFloat truncated = value;
5382
5383 bool ignored;
5384 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5385 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5386
5387 return truncated.bitwiseIsEqual(value);
5388}
5389
5390/// Checks whether the given value, which currently has the given
5391/// source semantics, has the same value when coerced through the
5392/// target semantics.
5393///
5394/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005395static bool IsSameFloatAfterCast(const APValue &value,
5396 const llvm::fltSemantics &Src,
5397 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005398 if (value.isFloat())
5399 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5400
5401 if (value.isVector()) {
5402 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5403 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5404 return false;
5405 return true;
5406 }
5407
5408 assert(value.isComplexFloat());
5409 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5410 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5411}
5412
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005413static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005414
Ted Kremenek6274be42010-09-23 21:43:44 +00005415static bool IsZero(Sema &S, Expr *E) {
5416 // Suppress cases where we are comparing against an enum constant.
5417 if (const DeclRefExpr *DR =
5418 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5419 if (isa<EnumConstantDecl>(DR->getDecl()))
5420 return false;
5421
5422 // Suppress cases where the '0' value is expanded from a macro.
5423 if (E->getLocStart().isMacroID())
5424 return false;
5425
John McCallcc7e5bf2010-05-06 08:58:33 +00005426 llvm::APSInt Value;
5427 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5428}
5429
John McCall2551c1b2010-10-06 00:25:24 +00005430static bool HasEnumType(Expr *E) {
5431 // Strip off implicit integral promotions.
5432 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005433 if (ICE->getCastKind() != CK_IntegralCast &&
5434 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005435 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005436 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005437 }
5438
5439 return E->getType()->isEnumeralType();
5440}
5441
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005442static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005443 // Disable warning in template instantiations.
5444 if (!S.ActiveTemplateInstantiations.empty())
5445 return;
5446
John McCalle3027922010-08-25 11:45:40 +00005447 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005448 if (E->isValueDependent())
5449 return;
5450
John McCalle3027922010-08-25 11:45:40 +00005451 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005452 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005453 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005454 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005455 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005456 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005457 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005458 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005459 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005460 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005461 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005462 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005463 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005464 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005465 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005466 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5467 }
5468}
5469
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005470static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005471 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005472 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005473 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005474 // Disable warning in template instantiations.
5475 if (!S.ActiveTemplateInstantiations.empty())
5476 return;
5477
Richard Trieu0f097742014-04-04 04:13:47 +00005478 // TODO: Investigate using GetExprRange() to get tighter bounds
5479 // on the bit ranges.
5480 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005481 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5482 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005483 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5484 unsigned OtherWidth = OtherRange.Width;
5485
5486 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5487
Richard Trieu560910c2012-11-14 22:50:24 +00005488 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005489 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005490 return;
5491
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005492 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005493 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005494
Richard Trieu0f097742014-04-04 04:13:47 +00005495 // Used for diagnostic printout.
5496 enum {
5497 LiteralConstant = 0,
5498 CXXBoolLiteralTrue,
5499 CXXBoolLiteralFalse
5500 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005501
Richard Trieu0f097742014-04-04 04:13:47 +00005502 if (!OtherIsBooleanType) {
5503 QualType ConstantT = Constant->getType();
5504 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005505
Richard Trieu0f097742014-04-04 04:13:47 +00005506 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5507 return;
5508 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5509 "comparison with non-integer type");
5510
5511 bool ConstantSigned = ConstantT->isSignedIntegerType();
5512 bool CommonSigned = CommonT->isSignedIntegerType();
5513
5514 bool EqualityOnly = false;
5515
5516 if (CommonSigned) {
5517 // The common type is signed, therefore no signed to unsigned conversion.
5518 if (!OtherRange.NonNegative) {
5519 // Check that the constant is representable in type OtherT.
5520 if (ConstantSigned) {
5521 if (OtherWidth >= Value.getMinSignedBits())
5522 return;
5523 } else { // !ConstantSigned
5524 if (OtherWidth >= Value.getActiveBits() + 1)
5525 return;
5526 }
5527 } else { // !OtherSigned
5528 // Check that the constant is representable in type OtherT.
5529 // Negative values are out of range.
5530 if (ConstantSigned) {
5531 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5532 return;
5533 } else { // !ConstantSigned
5534 if (OtherWidth >= Value.getActiveBits())
5535 return;
5536 }
Richard Trieu560910c2012-11-14 22:50:24 +00005537 }
Richard Trieu0f097742014-04-04 04:13:47 +00005538 } else { // !CommonSigned
5539 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005540 if (OtherWidth >= Value.getActiveBits())
5541 return;
Craig Toppercf360162014-06-18 05:13:11 +00005542 } else { // OtherSigned
5543 assert(!ConstantSigned &&
5544 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005545 // Check to see if the constant is representable in OtherT.
5546 if (OtherWidth > Value.getActiveBits())
5547 return;
5548 // Check to see if the constant is equivalent to a negative value
5549 // cast to CommonT.
5550 if (S.Context.getIntWidth(ConstantT) ==
5551 S.Context.getIntWidth(CommonT) &&
5552 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5553 return;
5554 // The constant value rests between values that OtherT can represent
5555 // after conversion. Relational comparison still works, but equality
5556 // comparisons will be tautological.
5557 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005558 }
5559 }
Richard Trieu0f097742014-04-04 04:13:47 +00005560
5561 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5562
5563 if (op == BO_EQ || op == BO_NE) {
5564 IsTrue = op == BO_NE;
5565 } else if (EqualityOnly) {
5566 return;
5567 } else if (RhsConstant) {
5568 if (op == BO_GT || op == BO_GE)
5569 IsTrue = !PositiveConstant;
5570 else // op == BO_LT || op == BO_LE
5571 IsTrue = PositiveConstant;
5572 } else {
5573 if (op == BO_LT || op == BO_LE)
5574 IsTrue = !PositiveConstant;
5575 else // op == BO_GT || op == BO_GE
5576 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005577 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005578 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005579 // Other isKnownToHaveBooleanValue
5580 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5581 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5582 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5583
5584 static const struct LinkedConditions {
5585 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5586 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5587 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5588 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5589 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5590 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5591
5592 } TruthTable = {
5593 // Constant on LHS. | Constant on RHS. |
5594 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5595 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5596 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5597 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5598 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5599 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5600 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5601 };
5602
5603 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5604
5605 enum ConstantValue ConstVal = Zero;
5606 if (Value.isUnsigned() || Value.isNonNegative()) {
5607 if (Value == 0) {
5608 LiteralOrBoolConstant =
5609 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5610 ConstVal = Zero;
5611 } else if (Value == 1) {
5612 LiteralOrBoolConstant =
5613 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5614 ConstVal = One;
5615 } else {
5616 LiteralOrBoolConstant = LiteralConstant;
5617 ConstVal = GT_One;
5618 }
5619 } else {
5620 ConstVal = LT_Zero;
5621 }
5622
5623 CompareBoolWithConstantResult CmpRes;
5624
5625 switch (op) {
5626 case BO_LT:
5627 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5628 break;
5629 case BO_GT:
5630 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5631 break;
5632 case BO_LE:
5633 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5634 break;
5635 case BO_GE:
5636 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5637 break;
5638 case BO_EQ:
5639 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5640 break;
5641 case BO_NE:
5642 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5643 break;
5644 default:
5645 CmpRes = Unkwn;
5646 break;
5647 }
5648
5649 if (CmpRes == AFals) {
5650 IsTrue = false;
5651 } else if (CmpRes == ATrue) {
5652 IsTrue = true;
5653 } else {
5654 return;
5655 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005656 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005657
5658 // If this is a comparison to an enum constant, include that
5659 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005660 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005661 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5662 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5663
5664 SmallString<64> PrettySourceValue;
5665 llvm::raw_svector_ostream OS(PrettySourceValue);
5666 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005667 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005668 else
5669 OS << Value;
5670
Richard Trieu0f097742014-04-04 04:13:47 +00005671 S.DiagRuntimeBehavior(
5672 E->getOperatorLoc(), E,
5673 S.PDiag(diag::warn_out_of_range_compare)
5674 << OS.str() << LiteralOrBoolConstant
5675 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5676 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005677}
5678
John McCallcc7e5bf2010-05-06 08:58:33 +00005679/// Analyze the operands of the given comparison. Implements the
5680/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005681static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005682 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5683 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005684}
John McCall263a48b2010-01-04 23:31:57 +00005685
John McCallca01b222010-01-04 23:21:16 +00005686/// \brief Implements -Wsign-compare.
5687///
Richard Trieu82402a02011-09-15 21:56:47 +00005688/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005689static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005690 // The type the comparison is being performed in.
5691 QualType T = E->getLHS()->getType();
5692 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5693 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005694 if (E->isValueDependent())
5695 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005696
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005697 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5698 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005699
5700 bool IsComparisonConstant = false;
5701
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005702 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005703 // of 'true' or 'false'.
5704 if (T->isIntegralType(S.Context)) {
5705 llvm::APSInt RHSValue;
5706 bool IsRHSIntegralLiteral =
5707 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5708 llvm::APSInt LHSValue;
5709 bool IsLHSIntegralLiteral =
5710 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5711 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5712 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5713 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5714 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5715 else
5716 IsComparisonConstant =
5717 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005718 } else if (!T->hasUnsignedIntegerRepresentation())
5719 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005720
John McCallcc7e5bf2010-05-06 08:58:33 +00005721 // We don't do anything special if this isn't an unsigned integral
5722 // comparison: we're only interested in integral comparisons, and
5723 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005724 //
5725 // We also don't care about value-dependent expressions or expressions
5726 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005727 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005728 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005729
John McCallcc7e5bf2010-05-06 08:58:33 +00005730 // Check to see if one of the (unmodified) operands is of different
5731 // signedness.
5732 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005733 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5734 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005735 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005736 signedOperand = LHS;
5737 unsignedOperand = RHS;
5738 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5739 signedOperand = RHS;
5740 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005741 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005742 CheckTrivialUnsignedComparison(S, E);
5743 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005744 }
5745
John McCallcc7e5bf2010-05-06 08:58:33 +00005746 // Otherwise, calculate the effective range of the signed operand.
5747 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005748
John McCallcc7e5bf2010-05-06 08:58:33 +00005749 // Go ahead and analyze implicit conversions in the operands. Note
5750 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005751 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5752 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005753
John McCallcc7e5bf2010-05-06 08:58:33 +00005754 // If the signed range is non-negative, -Wsign-compare won't fire,
5755 // but we should still check for comparisons which are always true
5756 // or false.
5757 if (signedRange.NonNegative)
5758 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005759
5760 // For (in)equality comparisons, if the unsigned operand is a
5761 // constant which cannot collide with a overflowed signed operand,
5762 // then reinterpreting the signed operand as unsigned will not
5763 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005764 if (E->isEqualityOp()) {
5765 unsigned comparisonWidth = S.Context.getIntWidth(T);
5766 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005767
John McCallcc7e5bf2010-05-06 08:58:33 +00005768 // We should never be unable to prove that the unsigned operand is
5769 // non-negative.
5770 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5771
5772 if (unsignedRange.Width < comparisonWidth)
5773 return;
5774 }
5775
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005776 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5777 S.PDiag(diag::warn_mixed_sign_comparison)
5778 << LHS->getType() << RHS->getType()
5779 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005780}
5781
John McCall1f425642010-11-11 03:21:53 +00005782/// Analyzes an attempt to assign the given value to a bitfield.
5783///
5784/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005785static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5786 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005787 assert(Bitfield->isBitField());
5788 if (Bitfield->isInvalidDecl())
5789 return false;
5790
John McCalldeebbcf2010-11-11 05:33:51 +00005791 // White-list bool bitfields.
5792 if (Bitfield->getType()->isBooleanType())
5793 return false;
5794
Douglas Gregor789adec2011-02-04 13:09:01 +00005795 // Ignore value- or type-dependent expressions.
5796 if (Bitfield->getBitWidth()->isValueDependent() ||
5797 Bitfield->getBitWidth()->isTypeDependent() ||
5798 Init->isValueDependent() ||
5799 Init->isTypeDependent())
5800 return false;
5801
John McCall1f425642010-11-11 03:21:53 +00005802 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5803
Richard Smith5fab0c92011-12-28 19:48:30 +00005804 llvm::APSInt Value;
5805 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005806 return false;
5807
John McCall1f425642010-11-11 03:21:53 +00005808 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005809 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005810
5811 if (OriginalWidth <= FieldWidth)
5812 return false;
5813
Eli Friedmanc267a322012-01-26 23:11:39 +00005814 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005815 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005816 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005817
Eli Friedmanc267a322012-01-26 23:11:39 +00005818 // Check whether the stored value is equal to the original value.
5819 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005820 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005821 return false;
5822
Eli Friedmanc267a322012-01-26 23:11:39 +00005823 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005824 // therefore don't strictly fit into a signed bitfield of width 1.
5825 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005826 return false;
5827
John McCall1f425642010-11-11 03:21:53 +00005828 std::string PrettyValue = Value.toString(10);
5829 std::string PrettyTrunc = TruncatedValue.toString(10);
5830
5831 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5832 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5833 << Init->getSourceRange();
5834
5835 return true;
5836}
5837
John McCalld2a53122010-11-09 23:24:47 +00005838/// Analyze the given simple or compound assignment for warning-worthy
5839/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005840static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005841 // Just recurse on the LHS.
5842 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5843
5844 // We want to recurse on the RHS as normal unless we're assigning to
5845 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005846 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005847 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005848 E->getOperatorLoc())) {
5849 // Recurse, ignoring any implicit conversions on the RHS.
5850 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5851 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005852 }
5853 }
5854
5855 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5856}
5857
John McCall263a48b2010-01-04 23:31:57 +00005858/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005859static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005860 SourceLocation CContext, unsigned diag,
5861 bool pruneControlFlow = false) {
5862 if (pruneControlFlow) {
5863 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5864 S.PDiag(diag)
5865 << SourceType << T << E->getSourceRange()
5866 << SourceRange(CContext));
5867 return;
5868 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005869 S.Diag(E->getExprLoc(), diag)
5870 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5871}
5872
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005873/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005874static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005875 SourceLocation CContext, unsigned diag,
5876 bool pruneControlFlow = false) {
5877 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005878}
5879
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005880/// Diagnose an implicit cast from a literal expression. Does not warn when the
5881/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005882void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5883 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005884 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005885 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005886 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005887 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5888 T->hasUnsignedIntegerRepresentation());
5889 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005890 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005891 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005892 return;
5893
Eli Friedman07185912013-08-29 23:44:43 +00005894 // FIXME: Force the precision of the source value down so we don't print
5895 // digits which are usually useless (we don't really care here if we
5896 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5897 // would automatically print the shortest representation, but it's a bit
5898 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005899 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005900 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5901 precision = (precision * 59 + 195) / 196;
5902 Value.toString(PrettySourceValue, precision);
5903
David Blaikie9b88cc02012-05-15 17:18:27 +00005904 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005905 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5906 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5907 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005908 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005909
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005910 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005911 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5912 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005913}
5914
John McCall18a2c2c2010-11-09 22:22:12 +00005915std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5916 if (!Range.Width) return "0";
5917
5918 llvm::APSInt ValueInRange = Value;
5919 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005920 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005921 return ValueInRange.toString(10);
5922}
5923
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005924static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5925 if (!isa<ImplicitCastExpr>(Ex))
5926 return false;
5927
5928 Expr *InnerE = Ex->IgnoreParenImpCasts();
5929 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5930 const Type *Source =
5931 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5932 if (Target->isDependentType())
5933 return false;
5934
5935 const BuiltinType *FloatCandidateBT =
5936 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5937 const Type *BoolCandidateType = ToBool ? Target : Source;
5938
5939 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5940 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5941}
5942
5943void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5944 SourceLocation CC) {
5945 unsigned NumArgs = TheCall->getNumArgs();
5946 for (unsigned i = 0; i < NumArgs; ++i) {
5947 Expr *CurrA = TheCall->getArg(i);
5948 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5949 continue;
5950
5951 bool IsSwapped = ((i > 0) &&
5952 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5953 IsSwapped |= ((i < (NumArgs - 1)) &&
5954 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5955 if (IsSwapped) {
5956 // Warn on this floating-point to bool conversion.
5957 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5958 CurrA->getType(), CC,
5959 diag::warn_impcast_floating_point_to_bool);
5960 }
5961 }
5962}
5963
John McCallcc7e5bf2010-05-06 08:58:33 +00005964void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005965 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005966 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005967
John McCallcc7e5bf2010-05-06 08:58:33 +00005968 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5969 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5970 if (Source == Target) return;
5971 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005972
Chandler Carruthc22845a2011-07-26 05:40:03 +00005973 // If the conversion context location is invalid don't complain. We also
5974 // don't want to emit a warning if the issue occurs from the expansion of
5975 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5976 // delay this check as long as possible. Once we detect we are in that
5977 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005978 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005979 return;
5980
Richard Trieu021baa32011-09-23 20:10:00 +00005981 // Diagnose implicit casts to bool.
5982 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5983 if (isa<StringLiteral>(E))
5984 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005985 // and expressions, for instance, assert(0 && "error here"), are
5986 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005987 return DiagnoseImpCast(S, E, T, CC,
5988 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005989 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5990 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5991 // This covers the literal expressions that evaluate to Objective-C
5992 // objects.
5993 return DiagnoseImpCast(S, E, T, CC,
5994 diag::warn_impcast_objective_c_literal_to_bool);
5995 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005996 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5997 // Warn on pointer to bool conversion that is always true.
5998 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5999 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006000 }
Richard Trieu021baa32011-09-23 20:10:00 +00006001 }
John McCall263a48b2010-01-04 23:31:57 +00006002
6003 // Strip vector types.
6004 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006005 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006006 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006007 return;
John McCallacf0ee52010-10-08 02:01:28 +00006008 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006009 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006010
6011 // If the vector cast is cast between two vectors of the same size, it is
6012 // a bitcast, not a conversion.
6013 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6014 return;
John McCall263a48b2010-01-04 23:31:57 +00006015
6016 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6017 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6018 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006019 if (auto VecTy = dyn_cast<VectorType>(Target))
6020 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006021
6022 // Strip complex types.
6023 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006024 if (!isa<ComplexType>(Target)) {
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 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006029 }
John McCall263a48b2010-01-04 23:31:57 +00006030
6031 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6032 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6033 }
6034
6035 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6036 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6037
6038 // If the source is floating point...
6039 if (SourceBT && SourceBT->isFloatingPoint()) {
6040 // ...and the target is floating point...
6041 if (TargetBT && TargetBT->isFloatingPoint()) {
6042 // ...then warn if we're dropping FP rank.
6043
6044 // Builtin FP kinds are ordered by increasing FP rank.
6045 if (SourceBT->getKind() > TargetBT->getKind()) {
6046 // Don't warn about float constants that are precisely
6047 // representable in the target type.
6048 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006049 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006050 // Value might be a float, a float vector, or a float complex.
6051 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006052 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6053 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006054 return;
6055 }
6056
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006057 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006058 return;
6059
John McCallacf0ee52010-10-08 02:01:28 +00006060 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006061 }
6062 return;
6063 }
6064
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006065 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006066 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006067 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006068 return;
6069
Chandler Carruth22c7a792011-02-17 11:05:49 +00006070 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006071 // We also want to warn on, e.g., "int i = -1.234"
6072 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6073 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6074 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6075
Chandler Carruth016ef402011-04-10 08:36:24 +00006076 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6077 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006078 } else {
6079 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6080 }
6081 }
John McCall263a48b2010-01-04 23:31:57 +00006082
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006083 // If the target is bool, warn if expr is a function or method call.
6084 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6085 isa<CallExpr>(E)) {
6086 // Check last argument of function call to see if it is an
6087 // implicit cast from a type matching the type the result
6088 // is being cast to.
6089 CallExpr *CEx = cast<CallExpr>(E);
6090 unsigned NumArgs = CEx->getNumArgs();
6091 if (NumArgs > 0) {
6092 Expr *LastA = CEx->getArg(NumArgs - 1);
6093 Expr *InnerE = LastA->IgnoreParenImpCasts();
6094 const Type *InnerType =
6095 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6096 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6097 // Warn on this floating-point to bool conversion
6098 DiagnoseImpCast(S, E, T, CC,
6099 diag::warn_impcast_floating_point_to_bool);
6100 }
6101 }
6102 }
John McCall263a48b2010-01-04 23:31:57 +00006103 return;
6104 }
6105
Richard Trieubeaf3452011-05-29 19:59:02 +00006106 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006107 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006108 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006109 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006110 SourceLocation Loc = E->getSourceRange().getBegin();
6111 if (Loc.isMacroID())
6112 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006113 if (!Loc.isMacroID() || CC.isMacroID())
6114 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6115 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006116 << FixItHint::CreateReplacement(Loc,
6117 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006118 }
6119
David Blaikie9366d2b2012-06-19 21:19:06 +00006120 if (!Source->isIntegerType() || !Target->isIntegerType())
6121 return;
6122
David Blaikie7555b6a2012-05-15 16:56:36 +00006123 // TODO: remove this early return once the false positives for constant->bool
6124 // in templates, macros, etc, are reduced or removed.
6125 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6126 return;
6127
John McCallcc7e5bf2010-05-06 08:58:33 +00006128 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006129 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006130
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006131 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006132 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006133 // TODO: this should happen for bitfield stores, too.
6134 llvm::APSInt Value(32);
6135 if (E->isIntegerConstantExpr(Value, S.Context)) {
6136 if (S.SourceMgr.isInSystemMacro(CC))
6137 return;
6138
John McCall18a2c2c2010-11-09 22:22:12 +00006139 std::string PrettySourceValue = Value.toString(10);
6140 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006141
Ted Kremenek33ba9952011-10-22 02:37:33 +00006142 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6143 S.PDiag(diag::warn_impcast_integer_precision_constant)
6144 << PrettySourceValue << PrettyTargetValue
6145 << E->getType() << T << E->getSourceRange()
6146 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006147 return;
6148 }
6149
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006150 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6151 if (S.SourceMgr.isInSystemMacro(CC))
6152 return;
6153
David Blaikie9455da02012-04-12 22:40:54 +00006154 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006155 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6156 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006157 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006158 }
6159
6160 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6161 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6162 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006163
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006164 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006165 return;
6166
John McCallcc7e5bf2010-05-06 08:58:33 +00006167 unsigned DiagID = diag::warn_impcast_integer_sign;
6168
6169 // Traditionally, gcc has warned about this under -Wsign-compare.
6170 // We also want to warn about it in -Wconversion.
6171 // So if -Wconversion is off, use a completely identical diagnostic
6172 // in the sign-compare group.
6173 // The conditional-checking code will
6174 if (ICContext) {
6175 DiagID = diag::warn_impcast_integer_sign_conditional;
6176 *ICContext = true;
6177 }
6178
John McCallacf0ee52010-10-08 02:01:28 +00006179 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006180 }
6181
Douglas Gregora78f1932011-02-22 02:45:07 +00006182 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006183 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6184 // type, to give us better diagnostics.
6185 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006186 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006187 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6188 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6189 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6190 SourceType = S.Context.getTypeDeclType(Enum);
6191 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6192 }
6193 }
6194
Douglas Gregora78f1932011-02-22 02:45:07 +00006195 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6196 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006197 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6198 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006199 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006200 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006201 return;
6202
Douglas Gregor364f7db2011-03-12 00:14:31 +00006203 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006204 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006205 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006206
John McCall263a48b2010-01-04 23:31:57 +00006207 return;
6208}
6209
David Blaikie18e9ac72012-05-15 21:57:38 +00006210void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6211 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006212
6213void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006214 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006215 E = E->IgnoreParenImpCasts();
6216
6217 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006218 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006219
John McCallacf0ee52010-10-08 02:01:28 +00006220 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006221 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006222 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006223 return;
6224}
6225
David Blaikie18e9ac72012-05-15 21:57:38 +00006226void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6227 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006228 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006229
6230 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006231 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6232 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006233
6234 // If -Wconversion would have warned about either of the candidates
6235 // for a signedness conversion to the context type...
6236 if (!Suspicious) return;
6237
6238 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006239 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006240 return;
6241
John McCallcc7e5bf2010-05-06 08:58:33 +00006242 // ...then check whether it would have warned about either of the
6243 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006244 if (E->getType() == T) return;
6245
6246 Suspicious = false;
6247 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6248 E->getType(), CC, &Suspicious);
6249 if (!Suspicious)
6250 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006251 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006252}
6253
6254/// AnalyzeImplicitConversions - Find and report any interesting
6255/// implicit conversions in the given expression. There are a couple
6256/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006257void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006258 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006259 Expr *E = OrigE->IgnoreParenImpCasts();
6260
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006261 if (E->isTypeDependent() || E->isValueDependent())
6262 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006263
John McCallcc7e5bf2010-05-06 08:58:33 +00006264 // For conditional operators, we analyze the arguments as if they
6265 // were being fed directly into the output.
6266 if (isa<ConditionalOperator>(E)) {
6267 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006268 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006269 return;
6270 }
6271
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006272 // Check implicit argument conversions for function calls.
6273 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6274 CheckImplicitArgumentConversions(S, Call, CC);
6275
John McCallcc7e5bf2010-05-06 08:58:33 +00006276 // Go ahead and check any implicit conversions we might have skipped.
6277 // The non-canonical typecheck is just an optimization;
6278 // CheckImplicitConversion will filter out dead implicit conversions.
6279 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006280 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006281
6282 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006283
6284 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006285 if (POE->getResultExpr())
6286 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006287 }
6288
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006289 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6290 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6291
John McCallcc7e5bf2010-05-06 08:58:33 +00006292 // Skip past explicit casts.
6293 if (isa<ExplicitCastExpr>(E)) {
6294 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006295 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006296 }
6297
John McCalld2a53122010-11-09 23:24:47 +00006298 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6299 // Do a somewhat different check with comparison operators.
6300 if (BO->isComparisonOp())
6301 return AnalyzeComparison(S, BO);
6302
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006303 // And with simple assignments.
6304 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006305 return AnalyzeAssignment(S, BO);
6306 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006307
6308 // These break the otherwise-useful invariant below. Fortunately,
6309 // we don't really need to recurse into them, because any internal
6310 // expressions should have been analyzed already when they were
6311 // built into statements.
6312 if (isa<StmtExpr>(E)) return;
6313
6314 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006315 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006316
6317 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006318 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006319 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006320 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006321 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006322 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006323 if (!ChildExpr)
6324 continue;
6325
Richard Trieu955231d2014-01-25 01:10:35 +00006326 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006327 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006328 // Ignore checking string literals that are in logical and operators.
6329 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006330 continue;
6331 AnalyzeImplicitConversions(S, ChildExpr, CC);
6332 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006333}
6334
6335} // end anonymous namespace
6336
Richard Trieu3bb8b562014-02-26 02:36:06 +00006337enum {
6338 AddressOf,
6339 FunctionPointer,
6340 ArrayPointer
6341};
6342
Richard Trieuc1888e02014-06-28 23:25:37 +00006343// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6344// Returns true when emitting a warning about taking the address of a reference.
6345static bool CheckForReference(Sema &SemaRef, const Expr *E,
6346 PartialDiagnostic PD) {
6347 E = E->IgnoreParenImpCasts();
6348
6349 const FunctionDecl *FD = nullptr;
6350
6351 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6352 if (!DRE->getDecl()->getType()->isReferenceType())
6353 return false;
6354 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6355 if (!M->getMemberDecl()->getType()->isReferenceType())
6356 return false;
6357 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6358 if (!Call->getCallReturnType()->isReferenceType())
6359 return false;
6360 FD = Call->getDirectCallee();
6361 } else {
6362 return false;
6363 }
6364
6365 SemaRef.Diag(E->getExprLoc(), PD);
6366
6367 // If possible, point to location of function.
6368 if (FD) {
6369 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6370 }
6371
6372 return true;
6373}
6374
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006375// Returns true if the SourceLocation is expanded from any macro body.
6376// Returns false if the SourceLocation is invalid, is from not in a macro
6377// expansion, or is from expanded from a top-level macro argument.
6378static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6379 if (Loc.isInvalid())
6380 return false;
6381
6382 while (Loc.isMacroID()) {
6383 if (SM.isMacroBodyExpansion(Loc))
6384 return true;
6385 Loc = SM.getImmediateMacroCallerLoc(Loc);
6386 }
6387
6388 return false;
6389}
6390
Richard Trieu3bb8b562014-02-26 02:36:06 +00006391/// \brief Diagnose pointers that are always non-null.
6392/// \param E the expression containing the pointer
6393/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6394/// compared to a null pointer
6395/// \param IsEqual True when the comparison is equal to a null pointer
6396/// \param Range Extra SourceRange to highlight in the diagnostic
6397void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6398 Expr::NullPointerConstantKind NullKind,
6399 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006400 if (!E)
6401 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006402
6403 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006404 if (E->getExprLoc().isMacroID()) {
6405 const SourceManager &SM = getSourceManager();
6406 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6407 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006408 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006409 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006410 E = E->IgnoreImpCasts();
6411
6412 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6413
Richard Trieuf7432752014-06-06 21:39:26 +00006414 if (isa<CXXThisExpr>(E)) {
6415 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6416 : diag::warn_this_bool_conversion;
6417 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6418 return;
6419 }
6420
Richard Trieu3bb8b562014-02-26 02:36:06 +00006421 bool IsAddressOf = false;
6422
6423 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6424 if (UO->getOpcode() != UO_AddrOf)
6425 return;
6426 IsAddressOf = true;
6427 E = UO->getSubExpr();
6428 }
6429
Richard Trieuc1888e02014-06-28 23:25:37 +00006430 if (IsAddressOf) {
6431 unsigned DiagID = IsCompare
6432 ? diag::warn_address_of_reference_null_compare
6433 : diag::warn_address_of_reference_bool_conversion;
6434 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6435 << IsEqual;
6436 if (CheckForReference(*this, E, PD)) {
6437 return;
6438 }
6439 }
6440
Richard Trieu3bb8b562014-02-26 02:36:06 +00006441 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006442 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006443 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6444 D = R->getDecl();
6445 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6446 D = M->getMemberDecl();
6447 }
6448
6449 // Weak Decls can be null.
6450 if (!D || D->isWeak())
6451 return;
6452
6453 QualType T = D->getType();
6454 const bool IsArray = T->isArrayType();
6455 const bool IsFunction = T->isFunctionType();
6456
Richard Trieuc1888e02014-06-28 23:25:37 +00006457 // Address of function is used to silence the function warning.
6458 if (IsAddressOf && IsFunction) {
6459 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006460 }
6461
6462 // Found nothing.
6463 if (!IsAddressOf && !IsFunction && !IsArray)
6464 return;
6465
6466 // Pretty print the expression for the diagnostic.
6467 std::string Str;
6468 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006469 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006470
6471 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6472 : diag::warn_impcast_pointer_to_bool;
6473 unsigned DiagType;
6474 if (IsAddressOf)
6475 DiagType = AddressOf;
6476 else if (IsFunction)
6477 DiagType = FunctionPointer;
6478 else if (IsArray)
6479 DiagType = ArrayPointer;
6480 else
6481 llvm_unreachable("Could not determine diagnostic.");
6482 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6483 << Range << IsEqual;
6484
6485 if (!IsFunction)
6486 return;
6487
6488 // Suggest '&' to silence the function warning.
6489 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6490 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6491
6492 // Check to see if '()' fixit should be emitted.
6493 QualType ReturnType;
6494 UnresolvedSet<4> NonTemplateOverloads;
6495 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6496 if (ReturnType.isNull())
6497 return;
6498
6499 if (IsCompare) {
6500 // There are two cases here. If there is null constant, the only suggest
6501 // for a pointer return type. If the null is 0, then suggest if the return
6502 // type is a pointer or an integer type.
6503 if (!ReturnType->isPointerType()) {
6504 if (NullKind == Expr::NPCK_ZeroExpression ||
6505 NullKind == Expr::NPCK_ZeroLiteral) {
6506 if (!ReturnType->isIntegerType())
6507 return;
6508 } else {
6509 return;
6510 }
6511 }
6512 } else { // !IsCompare
6513 // For function to bool, only suggest if the function pointer has bool
6514 // return type.
6515 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6516 return;
6517 }
6518 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006519 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006520}
6521
6522
John McCallcc7e5bf2010-05-06 08:58:33 +00006523/// Diagnoses "dangerous" implicit conversions within the given
6524/// expression (which is a full expression). Implements -Wconversion
6525/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006526///
6527/// \param CC the "context" location of the implicit conversion, i.e.
6528/// the most location of the syntactic entity requiring the implicit
6529/// conversion
6530void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006531 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006532 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006533 return;
6534
6535 // Don't diagnose for value- or type-dependent expressions.
6536 if (E->isTypeDependent() || E->isValueDependent())
6537 return;
6538
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006539 // Check for array bounds violations in cases where the check isn't triggered
6540 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6541 // ArraySubscriptExpr is on the RHS of a variable initialization.
6542 CheckArrayAccess(E);
6543
John McCallacf0ee52010-10-08 02:01:28 +00006544 // This is not the right CC for (e.g.) a variable initialization.
6545 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006546}
6547
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006548/// Diagnose when expression is an integer constant expression and its evaluation
6549/// results in integer overflow
6550void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006551 if (isa<BinaryOperator>(E->IgnoreParens()))
6552 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006553}
6554
Richard Smithc406cb72013-01-17 01:17:56 +00006555namespace {
6556/// \brief Visitor for expressions which looks for unsequenced operations on the
6557/// same object.
6558class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006559 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6560
Richard Smithc406cb72013-01-17 01:17:56 +00006561 /// \brief A tree of sequenced regions within an expression. Two regions are
6562 /// unsequenced if one is an ancestor or a descendent of the other. When we
6563 /// finish processing an expression with sequencing, such as a comma
6564 /// expression, we fold its tree nodes into its parent, since they are
6565 /// unsequenced with respect to nodes we will visit later.
6566 class SequenceTree {
6567 struct Value {
6568 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6569 unsigned Parent : 31;
6570 bool Merged : 1;
6571 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006572 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006573
6574 public:
6575 /// \brief A region within an expression which may be sequenced with respect
6576 /// to some other region.
6577 class Seq {
6578 explicit Seq(unsigned N) : Index(N) {}
6579 unsigned Index;
6580 friend class SequenceTree;
6581 public:
6582 Seq() : Index(0) {}
6583 };
6584
6585 SequenceTree() { Values.push_back(Value(0)); }
6586 Seq root() const { return Seq(0); }
6587
6588 /// \brief Create a new sequence of operations, which is an unsequenced
6589 /// subset of \p Parent. This sequence of operations is sequenced with
6590 /// respect to other children of \p Parent.
6591 Seq allocate(Seq Parent) {
6592 Values.push_back(Value(Parent.Index));
6593 return Seq(Values.size() - 1);
6594 }
6595
6596 /// \brief Merge a sequence of operations into its parent.
6597 void merge(Seq S) {
6598 Values[S.Index].Merged = true;
6599 }
6600
6601 /// \brief Determine whether two operations are unsequenced. This operation
6602 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6603 /// should have been merged into its parent as appropriate.
6604 bool isUnsequenced(Seq Cur, Seq Old) {
6605 unsigned C = representative(Cur.Index);
6606 unsigned Target = representative(Old.Index);
6607 while (C >= Target) {
6608 if (C == Target)
6609 return true;
6610 C = Values[C].Parent;
6611 }
6612 return false;
6613 }
6614
6615 private:
6616 /// \brief Pick a representative for a sequence.
6617 unsigned representative(unsigned K) {
6618 if (Values[K].Merged)
6619 // Perform path compression as we go.
6620 return Values[K].Parent = representative(Values[K].Parent);
6621 return K;
6622 }
6623 };
6624
6625 /// An object for which we can track unsequenced uses.
6626 typedef NamedDecl *Object;
6627
6628 /// Different flavors of object usage which we track. We only track the
6629 /// least-sequenced usage of each kind.
6630 enum UsageKind {
6631 /// A read of an object. Multiple unsequenced reads are OK.
6632 UK_Use,
6633 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006634 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006635 UK_ModAsValue,
6636 /// A modification of an object which is not sequenced before the value
6637 /// computation of the expression, such as n++.
6638 UK_ModAsSideEffect,
6639
6640 UK_Count = UK_ModAsSideEffect + 1
6641 };
6642
6643 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006644 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006645 Expr *Use;
6646 SequenceTree::Seq Seq;
6647 };
6648
6649 struct UsageInfo {
6650 UsageInfo() : Diagnosed(false) {}
6651 Usage Uses[UK_Count];
6652 /// Have we issued a diagnostic for this variable already?
6653 bool Diagnosed;
6654 };
6655 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6656
6657 Sema &SemaRef;
6658 /// Sequenced regions within the expression.
6659 SequenceTree Tree;
6660 /// Declaration modifications and references which we have seen.
6661 UsageInfoMap UsageMap;
6662 /// The region we are currently within.
6663 SequenceTree::Seq Region;
6664 /// Filled in with declarations which were modified as a side-effect
6665 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006666 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006667 /// Expressions to check later. We defer checking these to reduce
6668 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006669 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006670
6671 /// RAII object wrapping the visitation of a sequenced subexpression of an
6672 /// expression. At the end of this process, the side-effects of the evaluation
6673 /// become sequenced with respect to the value computation of the result, so
6674 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6675 /// UK_ModAsValue.
6676 struct SequencedSubexpression {
6677 SequencedSubexpression(SequenceChecker &Self)
6678 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6679 Self.ModAsSideEffect = &ModAsSideEffect;
6680 }
6681 ~SequencedSubexpression() {
6682 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6683 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6684 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6685 Self.addUsage(U, ModAsSideEffect[I].first,
6686 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6687 }
6688 Self.ModAsSideEffect = OldModAsSideEffect;
6689 }
6690
6691 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006692 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6693 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006694 };
6695
Richard Smith40238f02013-06-20 22:21:56 +00006696 /// RAII object wrapping the visitation of a subexpression which we might
6697 /// choose to evaluate as a constant. If any subexpression is evaluated and
6698 /// found to be non-constant, this allows us to suppress the evaluation of
6699 /// the outer expression.
6700 class EvaluationTracker {
6701 public:
6702 EvaluationTracker(SequenceChecker &Self)
6703 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6704 Self.EvalTracker = this;
6705 }
6706 ~EvaluationTracker() {
6707 Self.EvalTracker = Prev;
6708 if (Prev)
6709 Prev->EvalOK &= EvalOK;
6710 }
6711
6712 bool evaluate(const Expr *E, bool &Result) {
6713 if (!EvalOK || E->isValueDependent())
6714 return false;
6715 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6716 return EvalOK;
6717 }
6718
6719 private:
6720 SequenceChecker &Self;
6721 EvaluationTracker *Prev;
6722 bool EvalOK;
6723 } *EvalTracker;
6724
Richard Smithc406cb72013-01-17 01:17:56 +00006725 /// \brief Find the object which is produced by the specified expression,
6726 /// if any.
6727 Object getObject(Expr *E, bool Mod) const {
6728 E = E->IgnoreParenCasts();
6729 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6730 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6731 return getObject(UO->getSubExpr(), Mod);
6732 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6733 if (BO->getOpcode() == BO_Comma)
6734 return getObject(BO->getRHS(), Mod);
6735 if (Mod && BO->isAssignmentOp())
6736 return getObject(BO->getLHS(), Mod);
6737 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6738 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6739 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6740 return ME->getMemberDecl();
6741 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6742 // FIXME: If this is a reference, map through to its value.
6743 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006744 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006745 }
6746
6747 /// \brief Note that an object was modified or used by an expression.
6748 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6749 Usage &U = UI.Uses[UK];
6750 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6751 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6752 ModAsSideEffect->push_back(std::make_pair(O, U));
6753 U.Use = Ref;
6754 U.Seq = Region;
6755 }
6756 }
6757 /// \brief Check whether a modification or use conflicts with a prior usage.
6758 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6759 bool IsModMod) {
6760 if (UI.Diagnosed)
6761 return;
6762
6763 const Usage &U = UI.Uses[OtherKind];
6764 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6765 return;
6766
6767 Expr *Mod = U.Use;
6768 Expr *ModOrUse = Ref;
6769 if (OtherKind == UK_Use)
6770 std::swap(Mod, ModOrUse);
6771
6772 SemaRef.Diag(Mod->getExprLoc(),
6773 IsModMod ? diag::warn_unsequenced_mod_mod
6774 : diag::warn_unsequenced_mod_use)
6775 << O << SourceRange(ModOrUse->getExprLoc());
6776 UI.Diagnosed = true;
6777 }
6778
6779 void notePreUse(Object O, Expr *Use) {
6780 UsageInfo &U = UsageMap[O];
6781 // Uses conflict with other modifications.
6782 checkUsage(O, U, Use, UK_ModAsValue, false);
6783 }
6784 void notePostUse(Object O, Expr *Use) {
6785 UsageInfo &U = UsageMap[O];
6786 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6787 addUsage(U, O, Use, UK_Use);
6788 }
6789
6790 void notePreMod(Object O, Expr *Mod) {
6791 UsageInfo &U = UsageMap[O];
6792 // Modifications conflict with other modifications and with uses.
6793 checkUsage(O, U, Mod, UK_ModAsValue, true);
6794 checkUsage(O, U, Mod, UK_Use, false);
6795 }
6796 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6797 UsageInfo &U = UsageMap[O];
6798 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6799 addUsage(U, O, Use, UK);
6800 }
6801
6802public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006803 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006804 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6805 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006806 Visit(E);
6807 }
6808
6809 void VisitStmt(Stmt *S) {
6810 // Skip all statements which aren't expressions for now.
6811 }
6812
6813 void VisitExpr(Expr *E) {
6814 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006815 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006816 }
6817
6818 void VisitCastExpr(CastExpr *E) {
6819 Object O = Object();
6820 if (E->getCastKind() == CK_LValueToRValue)
6821 O = getObject(E->getSubExpr(), false);
6822
6823 if (O)
6824 notePreUse(O, E);
6825 VisitExpr(E);
6826 if (O)
6827 notePostUse(O, E);
6828 }
6829
6830 void VisitBinComma(BinaryOperator *BO) {
6831 // C++11 [expr.comma]p1:
6832 // Every value computation and side effect associated with the left
6833 // expression is sequenced before every value computation and side
6834 // effect associated with the right expression.
6835 SequenceTree::Seq LHS = Tree.allocate(Region);
6836 SequenceTree::Seq RHS = Tree.allocate(Region);
6837 SequenceTree::Seq OldRegion = Region;
6838
6839 {
6840 SequencedSubexpression SeqLHS(*this);
6841 Region = LHS;
6842 Visit(BO->getLHS());
6843 }
6844
6845 Region = RHS;
6846 Visit(BO->getRHS());
6847
6848 Region = OldRegion;
6849
6850 // Forget that LHS and RHS are sequenced. They are both unsequenced
6851 // with respect to other stuff.
6852 Tree.merge(LHS);
6853 Tree.merge(RHS);
6854 }
6855
6856 void VisitBinAssign(BinaryOperator *BO) {
6857 // The modification is sequenced after the value computation of the LHS
6858 // and RHS, so check it before inspecting the operands and update the
6859 // map afterwards.
6860 Object O = getObject(BO->getLHS(), true);
6861 if (!O)
6862 return VisitExpr(BO);
6863
6864 notePreMod(O, BO);
6865
6866 // C++11 [expr.ass]p7:
6867 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6868 // only once.
6869 //
6870 // Therefore, for a compound assignment operator, O is considered used
6871 // everywhere except within the evaluation of E1 itself.
6872 if (isa<CompoundAssignOperator>(BO))
6873 notePreUse(O, BO);
6874
6875 Visit(BO->getLHS());
6876
6877 if (isa<CompoundAssignOperator>(BO))
6878 notePostUse(O, BO);
6879
6880 Visit(BO->getRHS());
6881
Richard Smith83e37bee2013-06-26 23:16:51 +00006882 // C++11 [expr.ass]p1:
6883 // the assignment is sequenced [...] before the value computation of the
6884 // assignment expression.
6885 // C11 6.5.16/3 has no such rule.
6886 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6887 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006888 }
6889 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6890 VisitBinAssign(CAO);
6891 }
6892
6893 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6894 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6895 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6896 Object O = getObject(UO->getSubExpr(), true);
6897 if (!O)
6898 return VisitExpr(UO);
6899
6900 notePreMod(O, UO);
6901 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006902 // C++11 [expr.pre.incr]p1:
6903 // the expression ++x is equivalent to x+=1
6904 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6905 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006906 }
6907
6908 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6909 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6910 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6911 Object O = getObject(UO->getSubExpr(), true);
6912 if (!O)
6913 return VisitExpr(UO);
6914
6915 notePreMod(O, UO);
6916 Visit(UO->getSubExpr());
6917 notePostMod(O, UO, UK_ModAsSideEffect);
6918 }
6919
6920 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6921 void VisitBinLOr(BinaryOperator *BO) {
6922 // The side-effects of the LHS of an '&&' are sequenced before the
6923 // value computation of the RHS, and hence before the value computation
6924 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6925 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006926 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006927 {
6928 SequencedSubexpression Sequenced(*this);
6929 Visit(BO->getLHS());
6930 }
6931
6932 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006933 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006934 if (!Result)
6935 Visit(BO->getRHS());
6936 } else {
6937 // Check for unsequenced operations in the RHS, treating it as an
6938 // entirely separate evaluation.
6939 //
6940 // FIXME: If there are operations in the RHS which are unsequenced
6941 // with respect to operations outside the RHS, and those operations
6942 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006943 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006944 }
Richard Smithc406cb72013-01-17 01:17:56 +00006945 }
6946 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006947 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006948 {
6949 SequencedSubexpression Sequenced(*this);
6950 Visit(BO->getLHS());
6951 }
6952
6953 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006954 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006955 if (Result)
6956 Visit(BO->getRHS());
6957 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006958 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006959 }
Richard Smithc406cb72013-01-17 01:17:56 +00006960 }
6961
6962 // Only visit the condition, unless we can be sure which subexpression will
6963 // be chosen.
6964 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006965 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006966 {
6967 SequencedSubexpression Sequenced(*this);
6968 Visit(CO->getCond());
6969 }
Richard Smithc406cb72013-01-17 01:17:56 +00006970
6971 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006972 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006973 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006974 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006975 WorkList.push_back(CO->getTrueExpr());
6976 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006977 }
Richard Smithc406cb72013-01-17 01:17:56 +00006978 }
6979
Richard Smithe3dbfe02013-06-30 10:40:20 +00006980 void VisitCallExpr(CallExpr *CE) {
6981 // C++11 [intro.execution]p15:
6982 // When calling a function [...], every value computation and side effect
6983 // associated with any argument expression, or with the postfix expression
6984 // designating the called function, is sequenced before execution of every
6985 // expression or statement in the body of the function [and thus before
6986 // the value computation of its result].
6987 SequencedSubexpression Sequenced(*this);
6988 Base::VisitCallExpr(CE);
6989
6990 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6991 }
6992
Richard Smithc406cb72013-01-17 01:17:56 +00006993 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006994 // This is a call, so all subexpressions are sequenced before the result.
6995 SequencedSubexpression Sequenced(*this);
6996
Richard Smithc406cb72013-01-17 01:17:56 +00006997 if (!CCE->isListInitialization())
6998 return VisitExpr(CCE);
6999
7000 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007001 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007002 SequenceTree::Seq Parent = Region;
7003 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7004 E = CCE->arg_end();
7005 I != E; ++I) {
7006 Region = Tree.allocate(Parent);
7007 Elts.push_back(Region);
7008 Visit(*I);
7009 }
7010
7011 // Forget that the initializers are sequenced.
7012 Region = Parent;
7013 for (unsigned I = 0; I < Elts.size(); ++I)
7014 Tree.merge(Elts[I]);
7015 }
7016
7017 void VisitInitListExpr(InitListExpr *ILE) {
7018 if (!SemaRef.getLangOpts().CPlusPlus11)
7019 return VisitExpr(ILE);
7020
7021 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007022 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007023 SequenceTree::Seq Parent = Region;
7024 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7025 Expr *E = ILE->getInit(I);
7026 if (!E) continue;
7027 Region = Tree.allocate(Parent);
7028 Elts.push_back(Region);
7029 Visit(E);
7030 }
7031
7032 // Forget that the initializers are sequenced.
7033 Region = Parent;
7034 for (unsigned I = 0; I < Elts.size(); ++I)
7035 Tree.merge(Elts[I]);
7036 }
7037};
7038}
7039
7040void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007041 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007042 WorkList.push_back(E);
7043 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007044 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007045 SequenceChecker(*this, Item, WorkList);
7046 }
Richard Smithc406cb72013-01-17 01:17:56 +00007047}
7048
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007049void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7050 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007051 CheckImplicitConversions(E, CheckLoc);
7052 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007053 if (!IsConstexpr && !E->isValueDependent())
7054 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007055}
7056
John McCall1f425642010-11-11 03:21:53 +00007057void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7058 FieldDecl *BitField,
7059 Expr *Init) {
7060 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7061}
7062
Mike Stump0c2ec772010-01-21 03:59:47 +00007063/// CheckParmsForFunctionDef - Check that the parameters of the given
7064/// function are appropriate for the definition of a function. This
7065/// takes care of any checks that cannot be performed on the
7066/// declaration itself, e.g., that the types of each of the function
7067/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007068bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7069 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007070 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007071 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007072 for (; P != PEnd; ++P) {
7073 ParmVarDecl *Param = *P;
7074
Mike Stump0c2ec772010-01-21 03:59:47 +00007075 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7076 // function declarator that is part of a function definition of
7077 // that function shall not have incomplete type.
7078 //
7079 // This is also C++ [dcl.fct]p6.
7080 if (!Param->isInvalidDecl() &&
7081 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007082 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007083 Param->setInvalidDecl();
7084 HasInvalidParm = true;
7085 }
7086
7087 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7088 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007089 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007090 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007091 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007092 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007093 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007094
7095 // C99 6.7.5.3p12:
7096 // If the function declarator is not part of a definition of that
7097 // function, parameters may have incomplete type and may use the [*]
7098 // notation in their sequences of declarator specifiers to specify
7099 // variable length array types.
7100 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007101 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007102 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007103 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007104 // information is added for it.
7105 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007106 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007107 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007108 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007109 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007110
7111 // MSVC destroys objects passed by value in the callee. Therefore a
7112 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007113 // object's destructor. However, we don't perform any direct access check
7114 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007115 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7116 .getCXXABI()
7117 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007118 if (!Param->isInvalidDecl()) {
7119 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7120 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7121 if (!ClassDecl->isInvalidDecl() &&
7122 !ClassDecl->hasIrrelevantDestructor() &&
7123 !ClassDecl->isDependentContext()) {
7124 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7125 MarkFunctionReferenced(Param->getLocation(), Destructor);
7126 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7127 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007128 }
7129 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007130 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007131 }
7132
7133 return HasInvalidParm;
7134}
John McCall2b5c1b22010-08-12 21:44:57 +00007135
7136/// CheckCastAlign - Implements -Wcast-align, which warns when a
7137/// pointer cast increases the alignment requirements.
7138void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7139 // This is actually a lot of work to potentially be doing on every
7140 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007141 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007142 return;
7143
7144 // Ignore dependent types.
7145 if (T->isDependentType() || Op->getType()->isDependentType())
7146 return;
7147
7148 // Require that the destination be a pointer type.
7149 const PointerType *DestPtr = T->getAs<PointerType>();
7150 if (!DestPtr) return;
7151
7152 // If the destination has alignment 1, we're done.
7153 QualType DestPointee = DestPtr->getPointeeType();
7154 if (DestPointee->isIncompleteType()) return;
7155 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7156 if (DestAlign.isOne()) return;
7157
7158 // Require that the source be a pointer type.
7159 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7160 if (!SrcPtr) return;
7161 QualType SrcPointee = SrcPtr->getPointeeType();
7162
7163 // Whitelist casts from cv void*. We already implicitly
7164 // whitelisted casts to cv void*, since they have alignment 1.
7165 // Also whitelist casts involving incomplete types, which implicitly
7166 // includes 'void'.
7167 if (SrcPointee->isIncompleteType()) return;
7168
7169 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7170 if (SrcAlign >= DestAlign) return;
7171
7172 Diag(TRange.getBegin(), diag::warn_cast_align)
7173 << Op->getType() << T
7174 << static_cast<unsigned>(SrcAlign.getQuantity())
7175 << static_cast<unsigned>(DestAlign.getQuantity())
7176 << TRange << Op->getSourceRange();
7177}
7178
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007179static const Type* getElementType(const Expr *BaseExpr) {
7180 const Type* EltType = BaseExpr->getType().getTypePtr();
7181 if (EltType->isAnyPointerType())
7182 return EltType->getPointeeType().getTypePtr();
7183 else if (EltType->isArrayType())
7184 return EltType->getBaseElementTypeUnsafe();
7185 return EltType;
7186}
7187
Chandler Carruth28389f02011-08-05 09:10:50 +00007188/// \brief Check whether this array fits the idiom of a size-one tail padded
7189/// array member of a struct.
7190///
7191/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7192/// commonly used to emulate flexible arrays in C89 code.
7193static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7194 const NamedDecl *ND) {
7195 if (Size != 1 || !ND) return false;
7196
7197 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7198 if (!FD) return false;
7199
7200 // Don't consider sizes resulting from macro expansions or template argument
7201 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007202
7203 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007204 while (TInfo) {
7205 TypeLoc TL = TInfo->getTypeLoc();
7206 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007207 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7208 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007209 TInfo = TDL->getTypeSourceInfo();
7210 continue;
7211 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007212 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7213 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007214 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7215 return false;
7216 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007217 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007218 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007219
7220 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007221 if (!RD) return false;
7222 if (RD->isUnion()) return false;
7223 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7224 if (!CRD->isStandardLayout()) return false;
7225 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007226
Benjamin Kramer8c543672011-08-06 03:04:42 +00007227 // See if this is the last field decl in the record.
7228 const Decl *D = FD;
7229 while ((D = D->getNextDeclInContext()))
7230 if (isa<FieldDecl>(D))
7231 return false;
7232 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007233}
7234
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007235void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007236 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007237 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007238 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007239 if (IndexExpr->isValueDependent())
7240 return;
7241
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007242 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007243 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007244 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007245 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007246 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007247 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007248
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007249 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007250 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007251 return;
Richard Smith13f67182011-12-16 19:31:14 +00007252 if (IndexNegated)
7253 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007254
Craig Topperc3ec1492014-05-26 06:22:03 +00007255 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007256 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7257 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007258 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007259 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007260
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007261 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007262 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007263 if (!size.isStrictlyPositive())
7264 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007265
7266 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007267 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007268 // Make sure we're comparing apples to apples when comparing index to size
7269 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7270 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007271 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007272 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007273 if (ptrarith_typesize != array_typesize) {
7274 // There's a cast to a different size type involved
7275 uint64_t ratio = array_typesize / ptrarith_typesize;
7276 // TODO: Be smarter about handling cases where array_typesize is not a
7277 // multiple of ptrarith_typesize
7278 if (ptrarith_typesize * ratio == array_typesize)
7279 size *= llvm::APInt(size.getBitWidth(), ratio);
7280 }
7281 }
7282
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007283 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007284 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007285 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007286 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007287
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007288 // For array subscripting the index must be less than size, but for pointer
7289 // arithmetic also allow the index (offset) to be equal to size since
7290 // computing the next address after the end of the array is legal and
7291 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007292 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007293 return;
7294
7295 // Also don't warn for arrays of size 1 which are members of some
7296 // structure. These are often used to approximate flexible arrays in C89
7297 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007298 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007299 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007300
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007301 // Suppress the warning if the subscript expression (as identified by the
7302 // ']' location) and the index expression are both from macro expansions
7303 // within a system header.
7304 if (ASE) {
7305 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7306 ASE->getRBracketLoc());
7307 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7308 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7309 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007310 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007311 return;
7312 }
7313 }
7314
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007315 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007316 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007317 DiagID = diag::warn_array_index_exceeds_bounds;
7318
7319 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7320 PDiag(DiagID) << index.toString(10, true)
7321 << size.toString(10, true)
7322 << (unsigned)size.getLimitedValue(~0U)
7323 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007324 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007325 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007326 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007327 DiagID = diag::warn_ptr_arith_precedes_bounds;
7328 if (index.isNegative()) index = -index;
7329 }
7330
7331 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7332 PDiag(DiagID) << index.toString(10, true)
7333 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007334 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007335
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007336 if (!ND) {
7337 // Try harder to find a NamedDecl to point at in the note.
7338 while (const ArraySubscriptExpr *ASE =
7339 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7340 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7341 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7342 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7343 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7344 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7345 }
7346
Chandler Carruth1af88f12011-02-17 21:10:52 +00007347 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007348 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7349 PDiag(diag::note_array_index_out_of_bounds)
7350 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007351}
7352
Ted Kremenekdf26df72011-03-01 18:41:00 +00007353void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007354 int AllowOnePastEnd = 0;
7355 while (expr) {
7356 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007357 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007358 case Stmt::ArraySubscriptExprClass: {
7359 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007360 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007361 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007362 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007363 }
7364 case Stmt::UnaryOperatorClass: {
7365 // Only unwrap the * and & unary operators
7366 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7367 expr = UO->getSubExpr();
7368 switch (UO->getOpcode()) {
7369 case UO_AddrOf:
7370 AllowOnePastEnd++;
7371 break;
7372 case UO_Deref:
7373 AllowOnePastEnd--;
7374 break;
7375 default:
7376 return;
7377 }
7378 break;
7379 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007380 case Stmt::ConditionalOperatorClass: {
7381 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7382 if (const Expr *lhs = cond->getLHS())
7383 CheckArrayAccess(lhs);
7384 if (const Expr *rhs = cond->getRHS())
7385 CheckArrayAccess(rhs);
7386 return;
7387 }
7388 default:
7389 return;
7390 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007391 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007392}
John McCall31168b02011-06-15 23:02:42 +00007393
7394//===--- CHECK: Objective-C retain cycles ----------------------------------//
7395
7396namespace {
7397 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007398 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007399 VarDecl *Variable;
7400 SourceRange Range;
7401 SourceLocation Loc;
7402 bool Indirect;
7403
7404 void setLocsFrom(Expr *e) {
7405 Loc = e->getExprLoc();
7406 Range = e->getSourceRange();
7407 }
7408 };
7409}
7410
7411/// Consider whether capturing the given variable can possibly lead to
7412/// a retain cycle.
7413static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007414 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007415 // lifetime. In MRR, it's captured strongly if the variable is
7416 // __block and has an appropriate type.
7417 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7418 return false;
7419
7420 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007421 if (ref)
7422 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007423 return true;
7424}
7425
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007426static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007427 while (true) {
7428 e = e->IgnoreParens();
7429 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7430 switch (cast->getCastKind()) {
7431 case CK_BitCast:
7432 case CK_LValueBitCast:
7433 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007434 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007435 e = cast->getSubExpr();
7436 continue;
7437
John McCall31168b02011-06-15 23:02:42 +00007438 default:
7439 return false;
7440 }
7441 }
7442
7443 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7444 ObjCIvarDecl *ivar = ref->getDecl();
7445 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7446 return false;
7447
7448 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007449 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007450 return false;
7451
7452 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7453 owner.Indirect = true;
7454 return true;
7455 }
7456
7457 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7458 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7459 if (!var) return false;
7460 return considerVariable(var, ref, owner);
7461 }
7462
John McCall31168b02011-06-15 23:02:42 +00007463 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7464 if (member->isArrow()) return false;
7465
7466 // Don't count this as an indirect ownership.
7467 e = member->getBase();
7468 continue;
7469 }
7470
John McCallfe96e0b2011-11-06 09:01:30 +00007471 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7472 // Only pay attention to pseudo-objects on property references.
7473 ObjCPropertyRefExpr *pre
7474 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7475 ->IgnoreParens());
7476 if (!pre) return false;
7477 if (pre->isImplicitProperty()) return false;
7478 ObjCPropertyDecl *property = pre->getExplicitProperty();
7479 if (!property->isRetaining() &&
7480 !(property->getPropertyIvarDecl() &&
7481 property->getPropertyIvarDecl()->getType()
7482 .getObjCLifetime() == Qualifiers::OCL_Strong))
7483 return false;
7484
7485 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007486 if (pre->isSuperReceiver()) {
7487 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7488 if (!owner.Variable)
7489 return false;
7490 owner.Loc = pre->getLocation();
7491 owner.Range = pre->getSourceRange();
7492 return true;
7493 }
John McCallfe96e0b2011-11-06 09:01:30 +00007494 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7495 ->getSourceExpr());
7496 continue;
7497 }
7498
John McCall31168b02011-06-15 23:02:42 +00007499 // Array ivars?
7500
7501 return false;
7502 }
7503}
7504
7505namespace {
7506 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7507 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7508 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007509 Context(Context), Variable(variable), Capturer(nullptr),
7510 VarWillBeReased(false) {}
7511 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007512 VarDecl *Variable;
7513 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007514 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007515
7516 void VisitDeclRefExpr(DeclRefExpr *ref) {
7517 if (ref->getDecl() == Variable && !Capturer)
7518 Capturer = ref;
7519 }
7520
John McCall31168b02011-06-15 23:02:42 +00007521 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7522 if (Capturer) return;
7523 Visit(ref->getBase());
7524 if (Capturer && ref->isFreeIvar())
7525 Capturer = ref;
7526 }
7527
7528 void VisitBlockExpr(BlockExpr *block) {
7529 // Look inside nested blocks
7530 if (block->getBlockDecl()->capturesVariable(Variable))
7531 Visit(block->getBlockDecl()->getBody());
7532 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007533
7534 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7535 if (Capturer) return;
7536 if (OVE->getSourceExpr())
7537 Visit(OVE->getSourceExpr());
7538 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007539 void VisitBinaryOperator(BinaryOperator *BinOp) {
7540 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7541 return;
7542 Expr *LHS = BinOp->getLHS();
7543 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7544 if (DRE->getDecl() != Variable)
7545 return;
7546 if (Expr *RHS = BinOp->getRHS()) {
7547 RHS = RHS->IgnoreParenCasts();
7548 llvm::APSInt Value;
7549 VarWillBeReased =
7550 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7551 }
7552 }
7553 }
John McCall31168b02011-06-15 23:02:42 +00007554 };
7555}
7556
7557/// Check whether the given argument is a block which captures a
7558/// variable.
7559static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7560 assert(owner.Variable && owner.Loc.isValid());
7561
7562 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007563
7564 // Look through [^{...} copy] and Block_copy(^{...}).
7565 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7566 Selector Cmd = ME->getSelector();
7567 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7568 e = ME->getInstanceReceiver();
7569 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007570 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007571 e = e->IgnoreParenCasts();
7572 }
7573 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7574 if (CE->getNumArgs() == 1) {
7575 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007576 if (Fn) {
7577 const IdentifierInfo *FnI = Fn->getIdentifier();
7578 if (FnI && FnI->isStr("_Block_copy")) {
7579 e = CE->getArg(0)->IgnoreParenCasts();
7580 }
7581 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007582 }
7583 }
7584
John McCall31168b02011-06-15 23:02:42 +00007585 BlockExpr *block = dyn_cast<BlockExpr>(e);
7586 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007587 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007588
7589 FindCaptureVisitor visitor(S.Context, owner.Variable);
7590 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007591 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007592}
7593
7594static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7595 RetainCycleOwner &owner) {
7596 assert(capturer);
7597 assert(owner.Variable && owner.Loc.isValid());
7598
7599 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7600 << owner.Variable << capturer->getSourceRange();
7601 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7602 << owner.Indirect << owner.Range;
7603}
7604
7605/// Check for a keyword selector that starts with the word 'add' or
7606/// 'set'.
7607static bool isSetterLikeSelector(Selector sel) {
7608 if (sel.isUnarySelector()) return false;
7609
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007610 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007611 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007612 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007613 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007614 else if (str.startswith("add")) {
7615 // Specially whitelist 'addOperationWithBlock:'.
7616 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7617 return false;
7618 str = str.substr(3);
7619 }
John McCall31168b02011-06-15 23:02:42 +00007620 else
7621 return false;
7622
7623 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007624 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007625}
7626
7627/// Check a message send to see if it's likely to cause a retain cycle.
7628void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7629 // Only check instance methods whose selector looks like a setter.
7630 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7631 return;
7632
7633 // Try to find a variable that the receiver is strongly owned by.
7634 RetainCycleOwner owner;
7635 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007636 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007637 return;
7638 } else {
7639 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7640 owner.Variable = getCurMethodDecl()->getSelfDecl();
7641 owner.Loc = msg->getSuperLoc();
7642 owner.Range = msg->getSuperLoc();
7643 }
7644
7645 // Check whether the receiver is captured by any of the arguments.
7646 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7647 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7648 return diagnoseRetainCycle(*this, capturer, owner);
7649}
7650
7651/// Check a property assign to see if it's likely to cause a retain cycle.
7652void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7653 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007654 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007655 return;
7656
7657 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7658 diagnoseRetainCycle(*this, capturer, owner);
7659}
7660
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007661void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7662 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007663 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007664 return;
7665
7666 // Because we don't have an expression for the variable, we have to set the
7667 // location explicitly here.
7668 Owner.Loc = Var->getLocation();
7669 Owner.Range = Var->getSourceRange();
7670
7671 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7672 diagnoseRetainCycle(*this, Capturer, Owner);
7673}
7674
Ted Kremenek9304da92012-12-21 08:04:28 +00007675static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7676 Expr *RHS, bool isProperty) {
7677 // Check if RHS is an Objective-C object literal, which also can get
7678 // immediately zapped in a weak reference. Note that we explicitly
7679 // allow ObjCStringLiterals, since those are designed to never really die.
7680 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007681
Ted Kremenek64873352012-12-21 22:46:35 +00007682 // This enum needs to match with the 'select' in
7683 // warn_objc_arc_literal_assign (off-by-1).
7684 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7685 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7686 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007687
7688 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007689 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007690 << (isProperty ? 0 : 1)
7691 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007692
7693 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007694}
7695
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007696static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7697 Qualifiers::ObjCLifetime LT,
7698 Expr *RHS, bool isProperty) {
7699 // Strip off any implicit cast added to get to the one ARC-specific.
7700 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7701 if (cast->getCastKind() == CK_ARCConsumeObject) {
7702 S.Diag(Loc, diag::warn_arc_retained_assign)
7703 << (LT == Qualifiers::OCL_ExplicitNone)
7704 << (isProperty ? 0 : 1)
7705 << RHS->getSourceRange();
7706 return true;
7707 }
7708 RHS = cast->getSubExpr();
7709 }
7710
7711 if (LT == Qualifiers::OCL_Weak &&
7712 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7713 return true;
7714
7715 return false;
7716}
7717
Ted Kremenekb36234d2012-12-21 08:04:20 +00007718bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7719 QualType LHS, Expr *RHS) {
7720 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7721
7722 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7723 return false;
7724
7725 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7726 return true;
7727
7728 return false;
7729}
7730
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007731void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7732 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007733 QualType LHSType;
7734 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007735 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007736 ObjCPropertyRefExpr *PRE
7737 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7738 if (PRE && !PRE->isImplicitProperty()) {
7739 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7740 if (PD)
7741 LHSType = PD->getType();
7742 }
7743
7744 if (LHSType.isNull())
7745 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007746
7747 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7748
7749 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007750 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007751 getCurFunction()->markSafeWeakUse(LHS);
7752 }
7753
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007754 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7755 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007756
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007757 // FIXME. Check for other life times.
7758 if (LT != Qualifiers::OCL_None)
7759 return;
7760
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007761 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007762 if (PRE->isImplicitProperty())
7763 return;
7764 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7765 if (!PD)
7766 return;
7767
Bill Wendling44426052012-12-20 19:22:21 +00007768 unsigned Attributes = PD->getPropertyAttributes();
7769 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007770 // when 'assign' attribute was not explicitly specified
7771 // by user, ignore it and rely on property type itself
7772 // for lifetime info.
7773 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7774 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7775 LHSType->isObjCRetainableType())
7776 return;
7777
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007778 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007779 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007780 Diag(Loc, diag::warn_arc_retained_property_assign)
7781 << RHS->getSourceRange();
7782 return;
7783 }
7784 RHS = cast->getSubExpr();
7785 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007786 }
Bill Wendling44426052012-12-20 19:22:21 +00007787 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007788 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7789 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007790 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007791 }
7792}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007793
7794//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7795
7796namespace {
7797bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7798 SourceLocation StmtLoc,
7799 const NullStmt *Body) {
7800 // Do not warn if the body is a macro that expands to nothing, e.g:
7801 //
7802 // #define CALL(x)
7803 // if (condition)
7804 // CALL(0);
7805 //
7806 if (Body->hasLeadingEmptyMacro())
7807 return false;
7808
7809 // Get line numbers of statement and body.
7810 bool StmtLineInvalid;
7811 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7812 &StmtLineInvalid);
7813 if (StmtLineInvalid)
7814 return false;
7815
7816 bool BodyLineInvalid;
7817 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7818 &BodyLineInvalid);
7819 if (BodyLineInvalid)
7820 return false;
7821
7822 // Warn if null statement and body are on the same line.
7823 if (StmtLine != BodyLine)
7824 return false;
7825
7826 return true;
7827}
7828} // Unnamed namespace
7829
7830void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7831 const Stmt *Body,
7832 unsigned DiagID) {
7833 // Since this is a syntactic check, don't emit diagnostic for template
7834 // instantiations, this just adds noise.
7835 if (CurrentInstantiationScope)
7836 return;
7837
7838 // The body should be a null statement.
7839 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7840 if (!NBody)
7841 return;
7842
7843 // Do the usual checks.
7844 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7845 return;
7846
7847 Diag(NBody->getSemiLoc(), DiagID);
7848 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7849}
7850
7851void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7852 const Stmt *PossibleBody) {
7853 assert(!CurrentInstantiationScope); // Ensured by caller
7854
7855 SourceLocation StmtLoc;
7856 const Stmt *Body;
7857 unsigned DiagID;
7858 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7859 StmtLoc = FS->getRParenLoc();
7860 Body = FS->getBody();
7861 DiagID = diag::warn_empty_for_body;
7862 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7863 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7864 Body = WS->getBody();
7865 DiagID = diag::warn_empty_while_body;
7866 } else
7867 return; // Neither `for' nor `while'.
7868
7869 // The body should be a null statement.
7870 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7871 if (!NBody)
7872 return;
7873
7874 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007875 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007876 return;
7877
7878 // Do the usual checks.
7879 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7880 return;
7881
7882 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7883 // noise level low, emit diagnostics only if for/while is followed by a
7884 // CompoundStmt, e.g.:
7885 // for (int i = 0; i < n; i++);
7886 // {
7887 // a(i);
7888 // }
7889 // or if for/while is followed by a statement with more indentation
7890 // than for/while itself:
7891 // for (int i = 0; i < n; i++);
7892 // a(i);
7893 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7894 if (!ProbableTypo) {
7895 bool BodyColInvalid;
7896 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7897 PossibleBody->getLocStart(),
7898 &BodyColInvalid);
7899 if (BodyColInvalid)
7900 return;
7901
7902 bool StmtColInvalid;
7903 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7904 S->getLocStart(),
7905 &StmtColInvalid);
7906 if (StmtColInvalid)
7907 return;
7908
7909 if (BodyCol > StmtCol)
7910 ProbableTypo = true;
7911 }
7912
7913 if (ProbableTypo) {
7914 Diag(NBody->getSemiLoc(), DiagID);
7915 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7916 }
7917}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007918
7919//===--- Layout compatibility ----------------------------------------------//
7920
7921namespace {
7922
7923bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7924
7925/// \brief Check if two enumeration types are layout-compatible.
7926bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7927 // C++11 [dcl.enum] p8:
7928 // Two enumeration types are layout-compatible if they have the same
7929 // underlying type.
7930 return ED1->isComplete() && ED2->isComplete() &&
7931 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7932}
7933
7934/// \brief Check if two fields are layout-compatible.
7935bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7936 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7937 return false;
7938
7939 if (Field1->isBitField() != Field2->isBitField())
7940 return false;
7941
7942 if (Field1->isBitField()) {
7943 // Make sure that the bit-fields are the same length.
7944 unsigned Bits1 = Field1->getBitWidthValue(C);
7945 unsigned Bits2 = Field2->getBitWidthValue(C);
7946
7947 if (Bits1 != Bits2)
7948 return false;
7949 }
7950
7951 return true;
7952}
7953
7954/// \brief Check if two standard-layout structs are layout-compatible.
7955/// (C++11 [class.mem] p17)
7956bool isLayoutCompatibleStruct(ASTContext &C,
7957 RecordDecl *RD1,
7958 RecordDecl *RD2) {
7959 // If both records are C++ classes, check that base classes match.
7960 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7961 // If one of records is a CXXRecordDecl we are in C++ mode,
7962 // thus the other one is a CXXRecordDecl, too.
7963 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7964 // Check number of base classes.
7965 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7966 return false;
7967
7968 // Check the base classes.
7969 for (CXXRecordDecl::base_class_const_iterator
7970 Base1 = D1CXX->bases_begin(),
7971 BaseEnd1 = D1CXX->bases_end(),
7972 Base2 = D2CXX->bases_begin();
7973 Base1 != BaseEnd1;
7974 ++Base1, ++Base2) {
7975 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7976 return false;
7977 }
7978 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7979 // If only RD2 is a C++ class, it should have zero base classes.
7980 if (D2CXX->getNumBases() > 0)
7981 return false;
7982 }
7983
7984 // Check the fields.
7985 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7986 Field2End = RD2->field_end(),
7987 Field1 = RD1->field_begin(),
7988 Field1End = RD1->field_end();
7989 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7990 if (!isLayoutCompatible(C, *Field1, *Field2))
7991 return false;
7992 }
7993 if (Field1 != Field1End || Field2 != Field2End)
7994 return false;
7995
7996 return true;
7997}
7998
7999/// \brief Check if two standard-layout unions are layout-compatible.
8000/// (C++11 [class.mem] p18)
8001bool isLayoutCompatibleUnion(ASTContext &C,
8002 RecordDecl *RD1,
8003 RecordDecl *RD2) {
8004 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008005 for (auto *Field2 : RD2->fields())
8006 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008007
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008008 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008009 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8010 I = UnmatchedFields.begin(),
8011 E = UnmatchedFields.end();
8012
8013 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008014 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008015 bool Result = UnmatchedFields.erase(*I);
8016 (void) Result;
8017 assert(Result);
8018 break;
8019 }
8020 }
8021 if (I == E)
8022 return false;
8023 }
8024
8025 return UnmatchedFields.empty();
8026}
8027
8028bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8029 if (RD1->isUnion() != RD2->isUnion())
8030 return false;
8031
8032 if (RD1->isUnion())
8033 return isLayoutCompatibleUnion(C, RD1, RD2);
8034 else
8035 return isLayoutCompatibleStruct(C, RD1, RD2);
8036}
8037
8038/// \brief Check if two types are layout-compatible in C++11 sense.
8039bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8040 if (T1.isNull() || T2.isNull())
8041 return false;
8042
8043 // C++11 [basic.types] p11:
8044 // If two types T1 and T2 are the same type, then T1 and T2 are
8045 // layout-compatible types.
8046 if (C.hasSameType(T1, T2))
8047 return true;
8048
8049 T1 = T1.getCanonicalType().getUnqualifiedType();
8050 T2 = T2.getCanonicalType().getUnqualifiedType();
8051
8052 const Type::TypeClass TC1 = T1->getTypeClass();
8053 const Type::TypeClass TC2 = T2->getTypeClass();
8054
8055 if (TC1 != TC2)
8056 return false;
8057
8058 if (TC1 == Type::Enum) {
8059 return isLayoutCompatible(C,
8060 cast<EnumType>(T1)->getDecl(),
8061 cast<EnumType>(T2)->getDecl());
8062 } else if (TC1 == Type::Record) {
8063 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8064 return false;
8065
8066 return isLayoutCompatible(C,
8067 cast<RecordType>(T1)->getDecl(),
8068 cast<RecordType>(T2)->getDecl());
8069 }
8070
8071 return false;
8072}
8073}
8074
8075//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8076
8077namespace {
8078/// \brief Given a type tag expression find the type tag itself.
8079///
8080/// \param TypeExpr Type tag expression, as it appears in user's code.
8081///
8082/// \param VD Declaration of an identifier that appears in a type tag.
8083///
8084/// \param MagicValue Type tag magic value.
8085bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8086 const ValueDecl **VD, uint64_t *MagicValue) {
8087 while(true) {
8088 if (!TypeExpr)
8089 return false;
8090
8091 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8092
8093 switch (TypeExpr->getStmtClass()) {
8094 case Stmt::UnaryOperatorClass: {
8095 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8096 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8097 TypeExpr = UO->getSubExpr();
8098 continue;
8099 }
8100 return false;
8101 }
8102
8103 case Stmt::DeclRefExprClass: {
8104 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8105 *VD = DRE->getDecl();
8106 return true;
8107 }
8108
8109 case Stmt::IntegerLiteralClass: {
8110 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8111 llvm::APInt MagicValueAPInt = IL->getValue();
8112 if (MagicValueAPInt.getActiveBits() <= 64) {
8113 *MagicValue = MagicValueAPInt.getZExtValue();
8114 return true;
8115 } else
8116 return false;
8117 }
8118
8119 case Stmt::BinaryConditionalOperatorClass:
8120 case Stmt::ConditionalOperatorClass: {
8121 const AbstractConditionalOperator *ACO =
8122 cast<AbstractConditionalOperator>(TypeExpr);
8123 bool Result;
8124 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8125 if (Result)
8126 TypeExpr = ACO->getTrueExpr();
8127 else
8128 TypeExpr = ACO->getFalseExpr();
8129 continue;
8130 }
8131 return false;
8132 }
8133
8134 case Stmt::BinaryOperatorClass: {
8135 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8136 if (BO->getOpcode() == BO_Comma) {
8137 TypeExpr = BO->getRHS();
8138 continue;
8139 }
8140 return false;
8141 }
8142
8143 default:
8144 return false;
8145 }
8146 }
8147}
8148
8149/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8150///
8151/// \param TypeExpr Expression that specifies a type tag.
8152///
8153/// \param MagicValues Registered magic values.
8154///
8155/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8156/// kind.
8157///
8158/// \param TypeInfo Information about the corresponding C type.
8159///
8160/// \returns true if the corresponding C type was found.
8161bool GetMatchingCType(
8162 const IdentifierInfo *ArgumentKind,
8163 const Expr *TypeExpr, const ASTContext &Ctx,
8164 const llvm::DenseMap<Sema::TypeTagMagicValue,
8165 Sema::TypeTagData> *MagicValues,
8166 bool &FoundWrongKind,
8167 Sema::TypeTagData &TypeInfo) {
8168 FoundWrongKind = false;
8169
8170 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008171 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008172
8173 uint64_t MagicValue;
8174
8175 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8176 return false;
8177
8178 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008179 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008180 if (I->getArgumentKind() != ArgumentKind) {
8181 FoundWrongKind = true;
8182 return false;
8183 }
8184 TypeInfo.Type = I->getMatchingCType();
8185 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8186 TypeInfo.MustBeNull = I->getMustBeNull();
8187 return true;
8188 }
8189 return false;
8190 }
8191
8192 if (!MagicValues)
8193 return false;
8194
8195 llvm::DenseMap<Sema::TypeTagMagicValue,
8196 Sema::TypeTagData>::const_iterator I =
8197 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8198 if (I == MagicValues->end())
8199 return false;
8200
8201 TypeInfo = I->second;
8202 return true;
8203}
8204} // unnamed namespace
8205
8206void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8207 uint64_t MagicValue, QualType Type,
8208 bool LayoutCompatible,
8209 bool MustBeNull) {
8210 if (!TypeTagForDatatypeMagicValues)
8211 TypeTagForDatatypeMagicValues.reset(
8212 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8213
8214 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8215 (*TypeTagForDatatypeMagicValues)[Magic] =
8216 TypeTagData(Type, LayoutCompatible, MustBeNull);
8217}
8218
8219namespace {
8220bool IsSameCharType(QualType T1, QualType T2) {
8221 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8222 if (!BT1)
8223 return false;
8224
8225 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8226 if (!BT2)
8227 return false;
8228
8229 BuiltinType::Kind T1Kind = BT1->getKind();
8230 BuiltinType::Kind T2Kind = BT2->getKind();
8231
8232 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8233 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8234 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8235 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8236}
8237} // unnamed namespace
8238
8239void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8240 const Expr * const *ExprArgs) {
8241 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8242 bool IsPointerAttr = Attr->getIsPointer();
8243
8244 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8245 bool FoundWrongKind;
8246 TypeTagData TypeInfo;
8247 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8248 TypeTagForDatatypeMagicValues.get(),
8249 FoundWrongKind, TypeInfo)) {
8250 if (FoundWrongKind)
8251 Diag(TypeTagExpr->getExprLoc(),
8252 diag::warn_type_tag_for_datatype_wrong_kind)
8253 << TypeTagExpr->getSourceRange();
8254 return;
8255 }
8256
8257 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8258 if (IsPointerAttr) {
8259 // Skip implicit cast of pointer to `void *' (as a function argument).
8260 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008261 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008262 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008263 ArgumentExpr = ICE->getSubExpr();
8264 }
8265 QualType ArgumentType = ArgumentExpr->getType();
8266
8267 // Passing a `void*' pointer shouldn't trigger a warning.
8268 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8269 return;
8270
8271 if (TypeInfo.MustBeNull) {
8272 // Type tag with matching void type requires a null pointer.
8273 if (!ArgumentExpr->isNullPointerConstant(Context,
8274 Expr::NPC_ValueDependentIsNotNull)) {
8275 Diag(ArgumentExpr->getExprLoc(),
8276 diag::warn_type_safety_null_pointer_required)
8277 << ArgumentKind->getName()
8278 << ArgumentExpr->getSourceRange()
8279 << TypeTagExpr->getSourceRange();
8280 }
8281 return;
8282 }
8283
8284 QualType RequiredType = TypeInfo.Type;
8285 if (IsPointerAttr)
8286 RequiredType = Context.getPointerType(RequiredType);
8287
8288 bool mismatch = false;
8289 if (!TypeInfo.LayoutCompatible) {
8290 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8291
8292 // C++11 [basic.fundamental] p1:
8293 // Plain char, signed char, and unsigned char are three distinct types.
8294 //
8295 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8296 // char' depending on the current char signedness mode.
8297 if (mismatch)
8298 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8299 RequiredType->getPointeeType())) ||
8300 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8301 mismatch = false;
8302 } else
8303 if (IsPointerAttr)
8304 mismatch = !isLayoutCompatible(Context,
8305 ArgumentType->getPointeeType(),
8306 RequiredType->getPointeeType());
8307 else
8308 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8309
8310 if (mismatch)
8311 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008312 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008313 << TypeInfo.LayoutCompatible << RequiredType
8314 << ArgumentExpr->getSourceRange()
8315 << TypeTagExpr->getSourceRange();
8316}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008317