blob: 05eaaec5792ae1c1c3bd0be9dda81b95381ad9e6 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070035#include "llvm/ADT/STLExtras.h"
Richard Smith0e218972013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700104 ExprResult Arg(TheCall->getArg(0));
Richard Smith5154dce2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700109 TheCall->setArg(0, Arg.get());
Richard Smith5154dce2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Stephen Hines176edba2014-12-01 14:53:08 -0800114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
187 QualType ReturnTy = CE->getCallReturnType(S.Context);
188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCall60d7b3a2010-08-24 06:29:42 +0000227ExprResult
Stephen Hines176edba2014-12-01 14:53:08 -0800228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700230 ExprResult TheCallResult(TheCall);
Douglas Gregor2def4832008-11-17 20:34:05 +0000231
Chris Lattner946928f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssond406bf02009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000256 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000261 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner1b9a0792007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000284 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000304 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800305 case Builtin::BI__assume:
306 case Builtin::BI__builtin_assume:
307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000317 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000321 break;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
324 return ExprError();
325 break;
326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
329 return true;
330 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000331
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
335 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000336 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000339 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000340 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000346 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000352 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000358 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000364 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
Stephen Hines176edba2014-12-01 14:53:08 -0800370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000376 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000382 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000388 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000394 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000400 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -0800406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000418 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000424 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000430 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000436 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000442 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000443#define BUILTIN(ID, TYPE, ATTRS)
444#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000447#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000448 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000449 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000450 return ExprError();
451 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
454 return ExprError();
455 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
463 << "C++";
464 return ExprError();
465 }
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
469 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800470
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
482 break;
483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
485 break;
486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
489 break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700490
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
493 return ExprError();
494 break;
495
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
500 return ExprError();
501 break;
502 }
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
507 return ExprError();
508 break;
509 }
510
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
513 return ExprError();
514
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
518 TheCall))
519 return ExprError();
520
521 TheCall->setType(Context.VoidPtrTy);
522 break;
523
Nate Begeman26a31422010-06-08 02:47:44 +0000524 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700525
Nate Begeman26a31422010-06-08 02:47:44 +0000526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000529 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000530 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -0700531 case llvm::Triple::armeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000532 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -0700533 case llvm::Triple::thumbeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
535 return ExprError();
536 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000537 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700538 case llvm::Triple::aarch64_be:
Tim Northoverb793f0d2013-08-01 09:23:19 +0000539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
540 return ExprError();
541 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
556 return ExprError();
557 break;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
562 return ExprError();
563 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000564 default:
565 break;
566 }
567 }
568
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000569 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000570}
571
Nate Begeman61eecf52010-06-14 05:21:25 +0000572// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700573static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000574 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700575 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-11-08 01:16:11 +0000576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000586 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000587 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-11-08 01:16:11 +0000590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000599 }
David Blaikie7530c032012-01-17 06:56:22 +0000600 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000601}
602
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000603/// getNeonEltType - Return the QualType corresponding to the elements of
604/// the vector type specified by the NeonTypeFlags. This is used to check
605/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000606static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700607 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700616 if (IsInt64Long)
617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
618 else
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000621 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000623 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000625 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700626 return Context.UnsignedLongTy;
627 case NeonTypeFlags::Poly128:
628 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000629 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000630 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000631 case NeonTypeFlags::Float32:
632 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000633 case NeonTypeFlags::Float64:
634 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000635 }
David Blaikie7530c032012-01-17 06:56:22 +0000636 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000637}
638
Stephen Hines651f13c2014-04-23 16:59:28 -0700639bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000640 llvm::APSInt Result;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000641 uint64_t mask = 0;
642 unsigned TV = 0;
643 int PtrArgNum = -1;
644 bool HasConstPtr = false;
645 switch (BuiltinID) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700646#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000647#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700648#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000649 }
650
651 // For NEON intrinsics which are overloaded on vector element type, validate
652 // the immediate which specifies which variant to emit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700653 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000654 if (mask) {
655 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
656 return true;
657
658 TV = Result.getLimitedValue(64);
659 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
660 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Stephen Hines651f13c2014-04-23 16:59:28 -0700661 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-08-01 09:23:19 +0000662 }
663
664 if (PtrArgNum >= 0) {
665 // Check that pointer arguments have the specified type.
666 Expr *Arg = TheCall->getArg(PtrArgNum);
667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
668 Arg = ICE->getSubExpr();
669 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
670 QualType RHSTy = RHS.get()->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700671
672 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Stephen Hines176edba2014-12-01 14:53:08 -0800673 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Stephen Hines651f13c2014-04-23 16:59:28 -0700674 bool IsInt64Long =
675 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
676 QualType EltTy =
677 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000678 if (HasConstPtr)
679 EltTy = EltTy.withConst();
680 QualType LHSTy = Context.getPointerType(EltTy);
681 AssignConvertType ConvTy;
682 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
683 if (RHS.isInvalid())
684 return true;
685 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
686 RHS.get(), AA_Assigning))
687 return true;
688 }
689
690 // For NEON intrinsics which take an immediate value as part of the
691 // instruction, range check them here.
692 unsigned i = 0, l = 0, u = 0;
693 switch (BuiltinID) {
694 default:
695 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700696#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000697#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700698#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000699 }
Tim Northoverb793f0d2013-08-01 09:23:19 +0000700
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700701 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700702}
703
704bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
705 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000706 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700707 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700708 BuiltinID == ARM::BI__builtin_arm_strex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700709 BuiltinID == ARM::BI__builtin_arm_stlex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700710 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700711 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
712 BuiltinID == AArch64::BI__builtin_arm_strex ||
713 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000714 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700715 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700716 BuiltinID == ARM::BI__builtin_arm_ldaex ||
717 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
718 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover09df2b02013-07-16 09:47:53 +0000719
720 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
721
722 // Ensure that we have the proper number of arguments.
723 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
724 return true;
725
726 // Inspect the pointer argument of the atomic builtin. This should always be
727 // a pointer type, whose element is an integral scalar or pointer type.
728 // Because it is a pointer type, we don't have to worry about any implicit
729 // casts here.
730 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
731 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
732 if (PointerArgRes.isInvalid())
733 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700734 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000735
736 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
737 if (!pointerType) {
738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
739 << PointerArg->getType() << PointerArg->getSourceRange();
740 return true;
741 }
742
743 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
744 // task is to insert the appropriate casts into the AST. First work out just
745 // what the appropriate type is.
746 QualType ValType = pointerType->getPointeeType();
747 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
748 if (IsLdrex)
749 AddrType.addConst();
750
751 // Issue a warning if the cast is dodgy.
752 CastKind CastNeeded = CK_NoOp;
753 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
754 CastNeeded = CK_BitCast;
755 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
756 << PointerArg->getType()
757 << Context.getPointerType(AddrType)
758 << AA_Passing << PointerArg->getSourceRange();
759 }
760
761 // Finally, do the cast and replace the argument with the corrected version.
762 AddrType = Context.getPointerType(AddrType);
763 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
764 if (PointerArgRes.isInvalid())
765 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700766 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000767
768 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
769
770 // In general, we allow ints, floats and pointers to be loaded and stored.
771 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
772 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
773 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
774 << PointerArg->getType() << PointerArg->getSourceRange();
775 return true;
776 }
777
778 // But ARM doesn't have instructions to deal with 128-bit versions.
Stephen Hines651f13c2014-04-23 16:59:28 -0700779 if (Context.getTypeSize(ValType) > MaxWidth) {
780 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-07-16 09:47:53 +0000781 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
782 << PointerArg->getType() << PointerArg->getSourceRange();
783 return true;
784 }
785
786 switch (ValType.getObjCLifetime()) {
787 case Qualifiers::OCL_None:
788 case Qualifiers::OCL_ExplicitNone:
789 // okay
790 break;
791
792 case Qualifiers::OCL_Weak:
793 case Qualifiers::OCL_Strong:
794 case Qualifiers::OCL_Autoreleasing:
795 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
796 << ValType << PointerArg->getSourceRange();
797 return true;
798 }
799
800
801 if (IsLdrex) {
802 TheCall->setType(ValType);
803 return false;
804 }
805
806 // Initialize the argument to be stored.
807 ExprResult ValArg = TheCall->getArg(0);
808 InitializedEntity Entity = InitializedEntity::InitializeParameter(
809 Context, ValType, /*consume*/ false);
810 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
811 if (ValArg.isInvalid())
812 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000813 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000814
815 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
816 // but the custom checker bypasses all default analysis.
817 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000818 return false;
819}
820
Nate Begeman26a31422010-06-08 02:47:44 +0000821bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000822 llvm::APSInt Result;
823
Tim Northover09df2b02013-07-16 09:47:53 +0000824 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700825 BuiltinID == ARM::BI__builtin_arm_ldaex ||
826 BuiltinID == ARM::BI__builtin_arm_strex ||
827 BuiltinID == ARM::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700828 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000829 }
830
Stephen Hines176edba2014-12-01 14:53:08 -0800831 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
832 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
833 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
834 }
835
Stephen Hines651f13c2014-04-23 16:59:28 -0700836 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
837 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000838
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700839 // For intrinsics which take an immediate value as part of the instruction,
840 // range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000841 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000842 switch (BuiltinID) {
843 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000844 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
845 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000846 case ARM::BI__builtin_arm_vcvtr_f:
847 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000848 case ARM::BI__builtin_arm_dmb:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700849 case ARM::BI__builtin_arm_dsb:
Stephen Hines176edba2014-12-01 14:53:08 -0800850 case ARM::BI__builtin_arm_isb:
851 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700852 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000853
Nate Begeman99c40bb2010-08-03 21:32:34 +0000854 // FIXME: VFP Intrinsics should error if VFP not present.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700855 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssond406bf02009-08-16 01:56:34 +0000856}
Daniel Dunbarde454282008-10-02 18:44:07 +0000857
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700858bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Stephen Hines651f13c2014-04-23 16:59:28 -0700859 CallExpr *TheCall) {
860 llvm::APSInt Result;
861
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700862 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700863 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
864 BuiltinID == AArch64::BI__builtin_arm_strex ||
865 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700866 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
867 }
868
Stephen Hines176edba2014-12-01 14:53:08 -0800869 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
870 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
871 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
872 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
873 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
874 }
875
Stephen Hines651f13c2014-04-23 16:59:28 -0700876 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
877 return true;
878
Stephen Hines176edba2014-12-01 14:53:08 -0800879 // For intrinsics which take an immediate value as part of the instruction,
880 // range check them here.
881 unsigned i = 0, l = 0, u = 0;
882 switch (BuiltinID) {
883 default: return false;
884 case AArch64::BI__builtin_arm_dmb:
885 case AArch64::BI__builtin_arm_dsb:
886 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
887 }
888
889 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700890}
891
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000892bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
893 unsigned i = 0, l = 0, u = 0;
894 switch (BuiltinID) {
895 default: return false;
896 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
897 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000898 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
899 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
900 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
901 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
902 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700903 }
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000904
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700905 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000906}
907
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700908bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
909 unsigned i = 0, l = 0, u = 0;
910 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
911 BuiltinID == PPC::BI__builtin_divdeu ||
912 BuiltinID == PPC::BI__builtin_bpermd;
913 bool IsTarget64Bit = Context.getTargetInfo()
914 .getTypeWidth(Context
915 .getTargetInfo()
916 .getIntPtrType()) == 64;
917 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
918 BuiltinID == PPC::BI__builtin_divweu ||
919 BuiltinID == PPC::BI__builtin_divde ||
920 BuiltinID == PPC::BI__builtin_divdeu;
921
922 if (Is64BitBltin && !IsTarget64Bit)
923 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
924 << TheCall->getSourceRange();
925
926 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
927 (BuiltinID == PPC::BI__builtin_bpermd &&
928 !Context.getTargetInfo().hasFeature("bpermd")))
929 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
930 << TheCall->getSourceRange();
931
932 switch (BuiltinID) {
933 default: return false;
934 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
935 case PPC::BI__builtin_altivec_crypto_vshasigmad:
936 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
937 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
938 case PPC::BI__builtin_tbegin:
939 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
940 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
941 case PPC::BI__builtin_tabortwc:
942 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
943 case PPC::BI__builtin_tabortwci:
944 case PPC::BI__builtin_tabortdci:
945 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
946 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
947 }
948 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
949}
950
951bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
952 CallExpr *TheCall) {
953 if (BuiltinID == SystemZ::BI__builtin_tabort) {
954 Expr *Arg = TheCall->getArg(0);
955 llvm::APSInt AbortCode(32);
956 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
957 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
958 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
959 << Arg->getSourceRange();
960 }
961
962 return false;
963}
964
Stephen Hines651f13c2014-04-23 16:59:28 -0700965bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700966 unsigned i = 0, l = 0, u = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700967 switch (BuiltinID) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700968 default: return false;
969 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700970 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
971 case X86::BI__builtin_ia32_vpermil2pd:
972 case X86::BI__builtin_ia32_vpermil2pd256:
973 case X86::BI__builtin_ia32_vpermil2ps:
974 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
975 case X86::BI__builtin_ia32_cmpb128_mask:
976 case X86::BI__builtin_ia32_cmpw128_mask:
977 case X86::BI__builtin_ia32_cmpd128_mask:
978 case X86::BI__builtin_ia32_cmpq128_mask:
979 case X86::BI__builtin_ia32_cmpb256_mask:
980 case X86::BI__builtin_ia32_cmpw256_mask:
981 case X86::BI__builtin_ia32_cmpd256_mask:
982 case X86::BI__builtin_ia32_cmpq256_mask:
983 case X86::BI__builtin_ia32_cmpb512_mask:
984 case X86::BI__builtin_ia32_cmpw512_mask:
985 case X86::BI__builtin_ia32_cmpd512_mask:
986 case X86::BI__builtin_ia32_cmpq512_mask:
987 case X86::BI__builtin_ia32_ucmpb128_mask:
988 case X86::BI__builtin_ia32_ucmpw128_mask:
989 case X86::BI__builtin_ia32_ucmpd128_mask:
990 case X86::BI__builtin_ia32_ucmpq128_mask:
991 case X86::BI__builtin_ia32_ucmpb256_mask:
992 case X86::BI__builtin_ia32_ucmpw256_mask:
993 case X86::BI__builtin_ia32_ucmpd256_mask:
994 case X86::BI__builtin_ia32_ucmpq256_mask:
995 case X86::BI__builtin_ia32_ucmpb512_mask:
996 case X86::BI__builtin_ia32_ucmpw512_mask:
997 case X86::BI__builtin_ia32_ucmpd512_mask:
998 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
999 case X86::BI__builtin_ia32_roundps:
1000 case X86::BI__builtin_ia32_roundpd:
1001 case X86::BI__builtin_ia32_roundps256:
1002 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1003 case X86::BI__builtin_ia32_roundss:
1004 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1005 case X86::BI__builtin_ia32_cmpps:
1006 case X86::BI__builtin_ia32_cmpss:
1007 case X86::BI__builtin_ia32_cmppd:
1008 case X86::BI__builtin_ia32_cmpsd:
1009 case X86::BI__builtin_ia32_cmpps256:
1010 case X86::BI__builtin_ia32_cmppd256:
1011 case X86::BI__builtin_ia32_cmpps512_mask:
1012 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
1013 case X86::BI__builtin_ia32_vpcomub:
1014 case X86::BI__builtin_ia32_vpcomuw:
1015 case X86::BI__builtin_ia32_vpcomud:
1016 case X86::BI__builtin_ia32_vpcomuq:
1017 case X86::BI__builtin_ia32_vpcomb:
1018 case X86::BI__builtin_ia32_vpcomw:
1019 case X86::BI__builtin_ia32_vpcomd:
1020 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Stephen Hines651f13c2014-04-23 16:59:28 -07001021 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001022 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Stephen Hines651f13c2014-04-23 16:59:28 -07001023}
1024
Richard Smith831421f2012-06-25 20:30:08 +00001025/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1026/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1027/// Returns true when the format fits the function and the FormatStringInfo has
1028/// been populated.
1029bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1030 FormatStringInfo *FSI) {
1031 FSI->HasVAListArg = Format->getFirstArg() == 0;
1032 FSI->FormatIdx = Format->getFormatIdx() - 1;
1033 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +00001034
Richard Smith831421f2012-06-25 20:30:08 +00001035 // The way the format attribute works in GCC, the implicit this argument
1036 // of member functions is counted. However, it doesn't appear in our own
1037 // lists, so decrement format_idx in that case.
1038 if (IsCXXMember) {
1039 if(FSI->FormatIdx == 0)
1040 return false;
1041 --FSI->FormatIdx;
1042 if (FSI->FirstDataArg != 0)
1043 --FSI->FirstDataArg;
1044 }
1045 return true;
1046}
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Stephen Hines651f13c2014-04-23 16:59:28 -07001048/// Checks if a the given expression evaluates to null.
1049///
1050/// \brief Returns true if the value evaluates to null.
1051static bool CheckNonNullExpr(Sema &S,
1052 const Expr *Expr) {
1053 // As a special case, transparent unions initialized with zero are
1054 // considered null for the purposes of the nonnull attribute.
1055 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1056 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1057 if (const CompoundLiteralExpr *CLE =
1058 dyn_cast<CompoundLiteralExpr>(Expr))
1059 if (const InitListExpr *ILE =
1060 dyn_cast<InitListExpr>(CLE->getInitializer()))
1061 Expr = ILE->getInit(0);
1062 }
1063
1064 bool Result;
1065 return (!Expr->isValueDependent() &&
1066 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1067 !Result);
1068}
1069
1070static void CheckNonNullArgument(Sema &S,
1071 const Expr *ArgExpr,
1072 SourceLocation CallSiteLoc) {
1073 if (CheckNonNullExpr(S, ArgExpr))
1074 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1075}
1076
Stephen Hines176edba2014-12-01 14:53:08 -08001077bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1078 FormatStringInfo FSI;
1079 if ((GetFormatStringType(Format) == FST_NSString) &&
1080 getFormatStringInfo(Format, false, &FSI)) {
1081 Idx = FSI.FormatIdx;
1082 return true;
1083 }
1084 return false;
1085}
1086/// \brief Diagnose use of %s directive in an NSString which is being passed
1087/// as formatting string to formatting method.
1088static void
1089DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1090 const NamedDecl *FDecl,
1091 Expr **Args,
1092 unsigned NumArgs) {
1093 unsigned Idx = 0;
1094 bool Format = false;
1095 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1096 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1097 Idx = 2;
1098 Format = true;
1099 }
1100 else
1101 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1102 if (S.GetFormatNSStringIdx(I, Idx)) {
1103 Format = true;
1104 break;
1105 }
1106 }
1107 if (!Format || NumArgs <= Idx)
1108 return;
1109 const Expr *FormatExpr = Args[Idx];
1110 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1111 FormatExpr = CSCE->getSubExpr();
1112 const StringLiteral *FormatString;
1113 if (const ObjCStringLiteral *OSL =
1114 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1115 FormatString = OSL->getString();
1116 else
1117 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1118 if (!FormatString)
1119 return;
1120 if (S.FormatStringHasSArg(FormatString)) {
1121 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1122 << "%s" << 1 << 1;
1123 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1124 << FDecl->getDeclName();
1125 }
1126}
1127
Stephen Hines651f13c2014-04-23 16:59:28 -07001128static void CheckNonNullArguments(Sema &S,
1129 const NamedDecl *FDecl,
Stephen Hines176edba2014-12-01 14:53:08 -08001130 ArrayRef<const Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001131 SourceLocation CallSiteLoc) {
1132 // Check the attributes attached to the method/function itself.
Stephen Hines176edba2014-12-01 14:53:08 -08001133 llvm::SmallBitVector NonNullArgs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001134 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001135 if (!NonNull->args_size()) {
1136 // Easy case: all pointer arguments are nonnull.
1137 for (const auto *Arg : Args)
1138 if (S.isValidPointerAttrType(Arg->getType()))
1139 CheckNonNullArgument(S, Arg, CallSiteLoc);
1140 return;
1141 }
1142
1143 for (unsigned Val : NonNull->args()) {
1144 if (Val >= Args.size())
1145 continue;
1146 if (NonNullArgs.empty())
1147 NonNullArgs.resize(Args.size());
1148 NonNullArgs.set(Val);
1149 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001150 }
1151
1152 // Check the attributes on the parameters.
1153 ArrayRef<ParmVarDecl*> parms;
1154 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1155 parms = FD->parameters();
1156 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1157 parms = MD->parameters();
1158
Stephen Hines176edba2014-12-01 14:53:08 -08001159 unsigned ArgIndex = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001160 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Stephen Hines176edba2014-12-01 14:53:08 -08001161 I != E; ++I, ++ArgIndex) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001162 const ParmVarDecl *PVD = *I;
Stephen Hines176edba2014-12-01 14:53:08 -08001163 if (PVD->hasAttr<NonNullAttr>() ||
1164 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1165 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001166 }
Stephen Hines176edba2014-12-01 14:53:08 -08001167
1168 // In case this is a variadic call, check any remaining arguments.
1169 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1170 if (NonNullArgs[ArgIndex])
1171 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001172}
1173
Richard Smith831421f2012-06-25 20:30:08 +00001174/// Handles the checks for format strings, non-POD arguments to vararg
1175/// functions, and NULL arguments passed to non-NULL parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07001176void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1177 unsigned NumParams, bool IsMemberFunction,
1178 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +00001179 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +00001180 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +00001181 if (CurContext->isDependentContext())
1182 return;
Daniel Dunbarde454282008-10-02 18:44:07 +00001183
Ted Kremenekc82faca2010-09-09 04:33:05 +00001184 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +00001185 llvm::SmallBitVector CheckedVarArgs;
1186 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001187 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001188 // Only create vector if there are format attributes.
1189 CheckedVarArgs.resize(Args.size());
1190
Stephen Hines651f13c2014-04-23 16:59:28 -07001191 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +00001192 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001193 }
Richard Smith0e218972013-08-05 18:49:43 +00001194 }
Richard Smith831421f2012-06-25 20:30:08 +00001195
1196 // Refuse POD arguments that weren't caught by the format string
1197 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +00001198 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001199 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001200 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +00001201 if (const Expr *Arg = Args[ArgIdx]) {
1202 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1203 checkVariadicArgument(Arg, CallType);
1204 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001205 }
Richard Smith0e218972013-08-05 18:49:43 +00001206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Richard Trieu0538f0e2013-06-22 00:20:41 +00001208 if (FDecl) {
Stephen Hines176edba2014-12-01 14:53:08 -08001209 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001210
Richard Trieu0538f0e2013-06-22 00:20:41 +00001211 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -07001212 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1213 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001214 }
Richard Smith831421f2012-06-25 20:30:08 +00001215}
1216
1217/// CheckConstructorCall - Check a constructor call for correctness and safety
1218/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001219void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1220 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +00001221 const FunctionProtoType *Proto,
1222 SourceLocation Loc) {
1223 VariadicCallType CallType =
1224 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -07001225 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-06-25 20:30:08 +00001226 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1227}
1228
1229/// CheckFunctionCall - Check a direct function call for various correctness
1230/// and safety properties not strictly enforced by the C type system.
1231bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1232 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +00001233 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1234 isa<CXXMethodDecl>(FDecl);
1235 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1236 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +00001237 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1238 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001239 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +00001240 Expr** Args = TheCall->getArgs();
1241 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +00001242 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +00001243 // If this is a call to a member operator, hide the first argument
1244 // from checkCall.
1245 // FIXME: Our choice of AST representation here is less than ideal.
1246 ++Args;
1247 --NumArgs;
1248 }
Stephen Hines176edba2014-12-01 14:53:08 -08001249 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith831421f2012-06-25 20:30:08 +00001250 IsMemberFunction, TheCall->getRParenLoc(),
1251 TheCall->getCallee()->getSourceRange(), CallType);
1252
1253 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1254 // None of the checks below are needed for functions that don't have
1255 // simple names (e.g., C++ conversion functions).
1256 if (!FnInfo)
1257 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001258
Stephen Hines651f13c2014-04-23 16:59:28 -07001259 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Stephen Hines176edba2014-12-01 14:53:08 -08001260 if (getLangOpts().ObjC1)
1261 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Stephen Hines651f13c2014-04-23 16:59:28 -07001262
Anna Zaks0a151a12012-01-17 00:37:07 +00001263 unsigned CMId = FDecl->getMemoryFunctionKind();
1264 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +00001265 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001266
Anna Zaksd9b859a2012-01-13 21:52:01 +00001267 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +00001268 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001269 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +00001270 else if (CMId == Builtin::BIstrncat)
1271 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +00001272 else
Anna Zaks0a151a12012-01-17 00:37:07 +00001273 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001274
Anders Carlssond406bf02009-08-16 01:56:34 +00001275 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001276}
1277
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001278bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001279 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +00001280 VariadicCallType CallType =
1281 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001282
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001283 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +00001284 /*IsMemberFunction=*/false,
1285 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001286
1287 return false;
1288}
1289
Richard Trieuf462b012013-06-20 21:03:13 +00001290bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1291 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001292 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1293 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +00001294 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001296 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +00001297 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +00001298 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Richard Trieuf462b012013-06-20 21:03:13 +00001300 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +00001301 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +00001302 CallType = VariadicDoesNotApply;
1303 } else if (Ty->isBlockPointerType()) {
1304 CallType = VariadicBlock;
1305 } else { // Ty->isFunctionPointerType()
1306 CallType = VariadicFunction;
1307 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001308 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +00001309
Stephen Hines176edba2014-12-01 14:53:08 -08001310 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1311 TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001312 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +00001313 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -07001314
Anders Carlssond406bf02009-08-16 01:56:34 +00001315 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001316}
1317
Richard Trieu0538f0e2013-06-22 00:20:41 +00001318/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1319/// such as function pointers returned from functions.
1320bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001321 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu0538f0e2013-06-22 00:20:41 +00001322 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001323 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +00001324
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001325 checkCall(/*FDecl=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001326 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001327 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +00001328 TheCall->getCallee()->getSourceRange(), CallType);
1329
1330 return false;
1331}
1332
Stephen Hines651f13c2014-04-23 16:59:28 -07001333static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1334 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1335 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1336 return false;
1337
1338 switch (Op) {
1339 case AtomicExpr::AO__c11_atomic_init:
1340 llvm_unreachable("There is no ordering argument for an init");
1341
1342 case AtomicExpr::AO__c11_atomic_load:
1343 case AtomicExpr::AO__atomic_load_n:
1344 case AtomicExpr::AO__atomic_load:
1345 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1346 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1347
1348 case AtomicExpr::AO__c11_atomic_store:
1349 case AtomicExpr::AO__atomic_store:
1350 case AtomicExpr::AO__atomic_store_n:
1351 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1352 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1353 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1354
1355 default:
1356 return true;
1357 }
1358}
1359
Richard Smithff34d402012-04-12 05:08:17 +00001360ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1361 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +00001362 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1363 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +00001364
Richard Smithff34d402012-04-12 05:08:17 +00001365 // All these operations take one of the following forms:
1366 enum {
1367 // C __c11_atomic_init(A *, C)
1368 Init,
1369 // C __c11_atomic_load(A *, int)
1370 Load,
1371 // void __atomic_load(A *, CP, int)
1372 Copy,
1373 // C __c11_atomic_add(A *, M, int)
1374 Arithmetic,
1375 // C __atomic_exchange_n(A *, CP, int)
1376 Xchg,
1377 // void __atomic_exchange(A *, C *, CP, int)
1378 GNUXchg,
1379 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1380 C11CmpXchg,
1381 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1382 GNUCmpXchg
1383 } Form = Init;
1384 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1385 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1386 // where:
1387 // C is an appropriate type,
1388 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1389 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1390 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1391 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +00001392
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001393 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1394 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1395 AtomicExpr::AO__atomic_load,
1396 "need to update code for modified C11 atomics");
Richard Smithff34d402012-04-12 05:08:17 +00001397 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1398 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1399 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1400 Op == AtomicExpr::AO__atomic_store_n ||
1401 Op == AtomicExpr::AO__atomic_exchange_n ||
1402 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1403 bool IsAddSub = false;
1404
1405 switch (Op) {
1406 case AtomicExpr::AO__c11_atomic_init:
1407 Form = Init;
1408 break;
1409
1410 case AtomicExpr::AO__c11_atomic_load:
1411 case AtomicExpr::AO__atomic_load_n:
1412 Form = Load;
1413 break;
1414
1415 case AtomicExpr::AO__c11_atomic_store:
1416 case AtomicExpr::AO__atomic_load:
1417 case AtomicExpr::AO__atomic_store:
1418 case AtomicExpr::AO__atomic_store_n:
1419 Form = Copy;
1420 break;
1421
1422 case AtomicExpr::AO__c11_atomic_fetch_add:
1423 case AtomicExpr::AO__c11_atomic_fetch_sub:
1424 case AtomicExpr::AO__atomic_fetch_add:
1425 case AtomicExpr::AO__atomic_fetch_sub:
1426 case AtomicExpr::AO__atomic_add_fetch:
1427 case AtomicExpr::AO__atomic_sub_fetch:
1428 IsAddSub = true;
1429 // Fall through.
1430 case AtomicExpr::AO__c11_atomic_fetch_and:
1431 case AtomicExpr::AO__c11_atomic_fetch_or:
1432 case AtomicExpr::AO__c11_atomic_fetch_xor:
1433 case AtomicExpr::AO__atomic_fetch_and:
1434 case AtomicExpr::AO__atomic_fetch_or:
1435 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00001436 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00001437 case AtomicExpr::AO__atomic_and_fetch:
1438 case AtomicExpr::AO__atomic_or_fetch:
1439 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00001440 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +00001441 Form = Arithmetic;
1442 break;
1443
1444 case AtomicExpr::AO__c11_atomic_exchange:
1445 case AtomicExpr::AO__atomic_exchange_n:
1446 Form = Xchg;
1447 break;
1448
1449 case AtomicExpr::AO__atomic_exchange:
1450 Form = GNUXchg;
1451 break;
1452
1453 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1454 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1455 Form = C11CmpXchg;
1456 break;
1457
1458 case AtomicExpr::AO__atomic_compare_exchange:
1459 case AtomicExpr::AO__atomic_compare_exchange_n:
1460 Form = GNUCmpXchg;
1461 break;
1462 }
1463
1464 // Check we have the right number of arguments.
1465 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +00001466 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001467 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001468 << TheCall->getCallee()->getSourceRange();
1469 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001470 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1471 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001472 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001473 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001474 << TheCall->getCallee()->getSourceRange();
1475 return ExprError();
1476 }
1477
Richard Smithff34d402012-04-12 05:08:17 +00001478 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001479 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001480 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1481 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1482 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001483 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001484 << Ptr->getType() << Ptr->getSourceRange();
1485 return ExprError();
1486 }
1487
Richard Smithff34d402012-04-12 05:08:17 +00001488 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1489 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1490 QualType ValType = AtomTy; // 'C'
1491 if (IsC11) {
1492 if (!AtomTy->isAtomicType()) {
1493 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1494 << Ptr->getType() << Ptr->getSourceRange();
1495 return ExprError();
1496 }
Richard Smithbc57b102012-09-15 06:09:58 +00001497 if (AtomTy.isConstQualified()) {
1498 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1499 << Ptr->getType() << Ptr->getSourceRange();
1500 return ExprError();
1501 }
Richard Smithff34d402012-04-12 05:08:17 +00001502 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001503 }
Eli Friedman276b0612011-10-11 02:20:01 +00001504
Richard Smithff34d402012-04-12 05:08:17 +00001505 // For an arithmetic operation, the implied arithmetic must be well-formed.
1506 if (Form == Arithmetic) {
1507 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1508 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1509 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1510 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1511 return ExprError();
1512 }
1513 if (!IsAddSub && !ValType->isIntegerType()) {
1514 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1515 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1516 return ExprError();
1517 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001518 if (IsC11 && ValType->isPointerType() &&
1519 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1520 diag::err_incomplete_type)) {
1521 return ExprError();
1522 }
Richard Smithff34d402012-04-12 05:08:17 +00001523 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1524 // For __atomic_*_n operations, the value type must be a scalar integral or
1525 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001526 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001527 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1528 return ExprError();
1529 }
1530
Eli Friedmana3d727b2013-09-11 03:49:34 +00001531 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1532 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001533 // For GNU atomics, require a trivially-copyable type. This is not part of
1534 // the GNU atomics specification, but we enforce it for sanity.
1535 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001536 << Ptr->getType() << Ptr->getSourceRange();
1537 return ExprError();
1538 }
1539
Richard Smithff34d402012-04-12 05:08:17 +00001540 // FIXME: For any builtin other than a load, the ValType must not be
1541 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001542
1543 switch (ValType.getObjCLifetime()) {
1544 case Qualifiers::OCL_None:
1545 case Qualifiers::OCL_ExplicitNone:
1546 // okay
1547 break;
1548
1549 case Qualifiers::OCL_Weak:
1550 case Qualifiers::OCL_Strong:
1551 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001552 // FIXME: Can this happen? By this point, ValType should be known
1553 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001554 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1555 << ValType << Ptr->getSourceRange();
1556 return ExprError();
1557 }
1558
1559 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001560 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001561 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001562 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001563 ResultType = Context.BoolTy;
1564
Richard Smithff34d402012-04-12 05:08:17 +00001565 // The type of a parameter passed 'by value'. In the GNU atomics, such
1566 // arguments are actually passed as pointers.
1567 QualType ByValType = ValType; // 'CP'
1568 if (!IsC11 && !IsN)
1569 ByValType = Ptr->getType();
1570
Eli Friedman276b0612011-10-11 02:20:01 +00001571 // The first argument --- the pointer --- has a fixed type; we
1572 // deduce the types of the rest of the arguments accordingly. Walk
1573 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001574 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001575 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001576 if (i < NumVals[Form] + 1) {
1577 switch (i) {
1578 case 1:
1579 // The second argument is the non-atomic operand. For arithmetic, this
1580 // is always passed by value, and for a compare_exchange it is always
1581 // passed by address. For the rest, GNU uses by-address and C11 uses
1582 // by-value.
1583 assert(Form != Load);
1584 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1585 Ty = ValType;
1586 else if (Form == Copy || Form == Xchg)
1587 Ty = ByValType;
1588 else if (Form == Arithmetic)
1589 Ty = Context.getPointerDiffType();
1590 else
1591 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1592 break;
1593 case 2:
1594 // The third argument to compare_exchange / GNU exchange is a
1595 // (pointer to a) desired value.
1596 Ty = ByValType;
1597 break;
1598 case 3:
1599 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1600 Ty = Context.BoolTy;
1601 break;
1602 }
Eli Friedman276b0612011-10-11 02:20:01 +00001603 } else {
1604 // The order(s) are always converted to int.
1605 Ty = Context.IntTy;
1606 }
Richard Smithff34d402012-04-12 05:08:17 +00001607
Eli Friedman276b0612011-10-11 02:20:01 +00001608 InitializedEntity Entity =
1609 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001610 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001611 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1612 if (Arg.isInvalid())
1613 return true;
1614 TheCall->setArg(i, Arg.get());
1615 }
1616
Richard Smithff34d402012-04-12 05:08:17 +00001617 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001618 SmallVector<Expr*, 5> SubExprs;
1619 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001620 switch (Form) {
1621 case Init:
1622 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001623 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001624 break;
1625 case Load:
1626 SubExprs.push_back(TheCall->getArg(1)); // Order
1627 break;
1628 case Copy:
1629 case Arithmetic:
1630 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001631 SubExprs.push_back(TheCall->getArg(2)); // Order
1632 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001633 break;
1634 case GNUXchg:
1635 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1636 SubExprs.push_back(TheCall->getArg(3)); // Order
1637 SubExprs.push_back(TheCall->getArg(1)); // Val1
1638 SubExprs.push_back(TheCall->getArg(2)); // Val2
1639 break;
1640 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001641 SubExprs.push_back(TheCall->getArg(3)); // Order
1642 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001643 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001644 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001645 break;
1646 case GNUCmpXchg:
1647 SubExprs.push_back(TheCall->getArg(4)); // Order
1648 SubExprs.push_back(TheCall->getArg(1)); // Val1
1649 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1650 SubExprs.push_back(TheCall->getArg(2)); // Val2
1651 SubExprs.push_back(TheCall->getArg(3)); // Weak
1652 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001653 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001654
1655 if (SubExprs.size() >= 2 && Form != Init) {
1656 llvm::APSInt Result(32);
1657 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1658 !isValidOrderingForOp(Result.getSExtValue(), Op))
1659 Diag(SubExprs[1]->getLocStart(),
1660 diag::warn_atomic_op_has_invalid_memory_order)
1661 << SubExprs[1]->getSourceRange();
1662 }
1663
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001664 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1665 SubExprs, ResultType, Op,
1666 TheCall->getRParenLoc());
1667
1668 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1669 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1670 Context.AtomicUsesUnsupportedLibcall(AE))
1671 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1672 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001673
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001674 return AE;
Eli Friedman276b0612011-10-11 02:20:01 +00001675}
1676
1677
John McCall5f8d6042011-08-27 01:09:30 +00001678/// checkBuiltinArgument - Given a call to a builtin function, perform
1679/// normal type-checking on the given argument, updating the call in
1680/// place. This is useful when a builtin function requires custom
1681/// type-checking for some of its arguments but not necessarily all of
1682/// them.
1683///
1684/// Returns true on error.
1685static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1686 FunctionDecl *Fn = E->getDirectCallee();
1687 assert(Fn && "builtin call without direct callee!");
1688
1689 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1690 InitializedEntity Entity =
1691 InitializedEntity::InitializeParameter(S.Context, Param);
1692
1693 ExprResult Arg = E->getArg(0);
1694 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1695 if (Arg.isInvalid())
1696 return true;
1697
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001698 E->setArg(ArgIndex, Arg.get());
John McCall5f8d6042011-08-27 01:09:30 +00001699 return false;
1700}
1701
Chris Lattner5caa3702009-05-08 06:58:22 +00001702/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1703/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1704/// type of its first argument. The main ActOnCallExpr routines have already
1705/// promoted the types of arguments because all of these calls are prototyped as
1706/// void(...).
1707///
1708/// This function goes through and does final semantic checking for these
1709/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001710ExprResult
1711Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001712 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001713 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1714 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1715
1716 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001717 if (TheCall->getNumArgs() < 1) {
1718 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1719 << 0 << 1 << TheCall->getNumArgs()
1720 << TheCall->getCallee()->getSourceRange();
1721 return ExprError();
1722 }
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Chris Lattner5caa3702009-05-08 06:58:22 +00001724 // Inspect the first argument of the atomic builtin. This should always be
1725 // a pointer type, whose element is an integral scalar or pointer type.
1726 // Because it is a pointer type, we don't have to worry about any implicit
1727 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001728 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001729 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001730 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1731 if (FirstArgResult.isInvalid())
1732 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001733 FirstArg = FirstArgResult.get();
Eli Friedman8c382062012-01-23 02:35:22 +00001734 TheCall->setArg(0, FirstArg);
1735
John McCallf85e1932011-06-15 23:02:42 +00001736 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1737 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1739 << FirstArg->getType() << FirstArg->getSourceRange();
1740 return ExprError();
1741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
John McCallf85e1932011-06-15 23:02:42 +00001743 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001744 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001745 !ValType->isBlockPointerType()) {
1746 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1747 << FirstArg->getType() << FirstArg->getSourceRange();
1748 return ExprError();
1749 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001750
John McCallf85e1932011-06-15 23:02:42 +00001751 switch (ValType.getObjCLifetime()) {
1752 case Qualifiers::OCL_None:
1753 case Qualifiers::OCL_ExplicitNone:
1754 // okay
1755 break;
1756
1757 case Qualifiers::OCL_Weak:
1758 case Qualifiers::OCL_Strong:
1759 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001761 << ValType << FirstArg->getSourceRange();
1762 return ExprError();
1763 }
1764
John McCallb45ae252011-10-05 07:41:44 +00001765 // Strip any qualifiers off ValType.
1766 ValType = ValType.getUnqualifiedType();
1767
Chandler Carruth8d13d222010-07-18 20:54:12 +00001768 // The majority of builtins return a value, but a few have special return
1769 // types, so allow them to override appropriately below.
1770 QualType ResultType = ValType;
1771
Chris Lattner5caa3702009-05-08 06:58:22 +00001772 // We need to figure out which concrete builtin this maps onto. For example,
1773 // __sync_fetch_and_add with a 2 byte object turns into
1774 // __sync_fetch_and_add_2.
1775#define BUILTIN_ROW(x) \
1776 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1777 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Chris Lattner5caa3702009-05-08 06:58:22 +00001779 static const unsigned BuiltinIndices[][5] = {
1780 BUILTIN_ROW(__sync_fetch_and_add),
1781 BUILTIN_ROW(__sync_fetch_and_sub),
1782 BUILTIN_ROW(__sync_fetch_and_or),
1783 BUILTIN_ROW(__sync_fetch_and_and),
1784 BUILTIN_ROW(__sync_fetch_and_xor),
Stephen Hines176edba2014-12-01 14:53:08 -08001785 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Chris Lattner5caa3702009-05-08 06:58:22 +00001787 BUILTIN_ROW(__sync_add_and_fetch),
1788 BUILTIN_ROW(__sync_sub_and_fetch),
1789 BUILTIN_ROW(__sync_and_and_fetch),
1790 BUILTIN_ROW(__sync_or_and_fetch),
1791 BUILTIN_ROW(__sync_xor_and_fetch),
Stephen Hines176edba2014-12-01 14:53:08 -08001792 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Chris Lattner5caa3702009-05-08 06:58:22 +00001794 BUILTIN_ROW(__sync_val_compare_and_swap),
1795 BUILTIN_ROW(__sync_bool_compare_and_swap),
1796 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001797 BUILTIN_ROW(__sync_lock_release),
1798 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001799 };
Mike Stump1eb44332009-09-09 15:08:12 +00001800#undef BUILTIN_ROW
1801
Chris Lattner5caa3702009-05-08 06:58:22 +00001802 // Determine the index of the size.
1803 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001804 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001805 case 1: SizeIndex = 0; break;
1806 case 2: SizeIndex = 1; break;
1807 case 4: SizeIndex = 2; break;
1808 case 8: SizeIndex = 3; break;
1809 case 16: SizeIndex = 4; break;
1810 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001811 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1812 << FirstArg->getType() << FirstArg->getSourceRange();
1813 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001814 }
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Chris Lattner5caa3702009-05-08 06:58:22 +00001816 // Each of these builtins has one pointer argument, followed by some number of
1817 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1818 // that we ignore. Find out which row of BuiltinIndices to read from as well
1819 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001820 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001821 unsigned BuiltinIndex, NumFixed = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08001822 bool WarnAboutSemanticsChange = false;
Chris Lattner5caa3702009-05-08 06:58:22 +00001823 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001824 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001825 case Builtin::BI__sync_fetch_and_add:
1826 case Builtin::BI__sync_fetch_and_add_1:
1827 case Builtin::BI__sync_fetch_and_add_2:
1828 case Builtin::BI__sync_fetch_and_add_4:
1829 case Builtin::BI__sync_fetch_and_add_8:
1830 case Builtin::BI__sync_fetch_and_add_16:
1831 BuiltinIndex = 0;
1832 break;
1833
1834 case Builtin::BI__sync_fetch_and_sub:
1835 case Builtin::BI__sync_fetch_and_sub_1:
1836 case Builtin::BI__sync_fetch_and_sub_2:
1837 case Builtin::BI__sync_fetch_and_sub_4:
1838 case Builtin::BI__sync_fetch_and_sub_8:
1839 case Builtin::BI__sync_fetch_and_sub_16:
1840 BuiltinIndex = 1;
1841 break;
1842
1843 case Builtin::BI__sync_fetch_and_or:
1844 case Builtin::BI__sync_fetch_and_or_1:
1845 case Builtin::BI__sync_fetch_and_or_2:
1846 case Builtin::BI__sync_fetch_and_or_4:
1847 case Builtin::BI__sync_fetch_and_or_8:
1848 case Builtin::BI__sync_fetch_and_or_16:
1849 BuiltinIndex = 2;
1850 break;
1851
1852 case Builtin::BI__sync_fetch_and_and:
1853 case Builtin::BI__sync_fetch_and_and_1:
1854 case Builtin::BI__sync_fetch_and_and_2:
1855 case Builtin::BI__sync_fetch_and_and_4:
1856 case Builtin::BI__sync_fetch_and_and_8:
1857 case Builtin::BI__sync_fetch_and_and_16:
1858 BuiltinIndex = 3;
1859 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregora9766412011-11-28 16:30:08 +00001861 case Builtin::BI__sync_fetch_and_xor:
1862 case Builtin::BI__sync_fetch_and_xor_1:
1863 case Builtin::BI__sync_fetch_and_xor_2:
1864 case Builtin::BI__sync_fetch_and_xor_4:
1865 case Builtin::BI__sync_fetch_and_xor_8:
1866 case Builtin::BI__sync_fetch_and_xor_16:
1867 BuiltinIndex = 4;
1868 break;
1869
Stephen Hines176edba2014-12-01 14:53:08 -08001870 case Builtin::BI__sync_fetch_and_nand:
1871 case Builtin::BI__sync_fetch_and_nand_1:
1872 case Builtin::BI__sync_fetch_and_nand_2:
1873 case Builtin::BI__sync_fetch_and_nand_4:
1874 case Builtin::BI__sync_fetch_and_nand_8:
1875 case Builtin::BI__sync_fetch_and_nand_16:
1876 BuiltinIndex = 5;
1877 WarnAboutSemanticsChange = true;
1878 break;
1879
Douglas Gregora9766412011-11-28 16:30:08 +00001880 case Builtin::BI__sync_add_and_fetch:
1881 case Builtin::BI__sync_add_and_fetch_1:
1882 case Builtin::BI__sync_add_and_fetch_2:
1883 case Builtin::BI__sync_add_and_fetch_4:
1884 case Builtin::BI__sync_add_and_fetch_8:
1885 case Builtin::BI__sync_add_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001886 BuiltinIndex = 6;
Douglas Gregora9766412011-11-28 16:30:08 +00001887 break;
1888
1889 case Builtin::BI__sync_sub_and_fetch:
1890 case Builtin::BI__sync_sub_and_fetch_1:
1891 case Builtin::BI__sync_sub_and_fetch_2:
1892 case Builtin::BI__sync_sub_and_fetch_4:
1893 case Builtin::BI__sync_sub_and_fetch_8:
1894 case Builtin::BI__sync_sub_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001895 BuiltinIndex = 7;
Douglas Gregora9766412011-11-28 16:30:08 +00001896 break;
1897
1898 case Builtin::BI__sync_and_and_fetch:
1899 case Builtin::BI__sync_and_and_fetch_1:
1900 case Builtin::BI__sync_and_and_fetch_2:
1901 case Builtin::BI__sync_and_and_fetch_4:
1902 case Builtin::BI__sync_and_and_fetch_8:
1903 case Builtin::BI__sync_and_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001904 BuiltinIndex = 8;
Douglas Gregora9766412011-11-28 16:30:08 +00001905 break;
1906
1907 case Builtin::BI__sync_or_and_fetch:
1908 case Builtin::BI__sync_or_and_fetch_1:
1909 case Builtin::BI__sync_or_and_fetch_2:
1910 case Builtin::BI__sync_or_and_fetch_4:
1911 case Builtin::BI__sync_or_and_fetch_8:
1912 case Builtin::BI__sync_or_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001913 BuiltinIndex = 9;
Douglas Gregora9766412011-11-28 16:30:08 +00001914 break;
1915
1916 case Builtin::BI__sync_xor_and_fetch:
1917 case Builtin::BI__sync_xor_and_fetch_1:
1918 case Builtin::BI__sync_xor_and_fetch_2:
1919 case Builtin::BI__sync_xor_and_fetch_4:
1920 case Builtin::BI__sync_xor_and_fetch_8:
1921 case Builtin::BI__sync_xor_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001922 BuiltinIndex = 10;
1923 break;
1924
1925 case Builtin::BI__sync_nand_and_fetch:
1926 case Builtin::BI__sync_nand_and_fetch_1:
1927 case Builtin::BI__sync_nand_and_fetch_2:
1928 case Builtin::BI__sync_nand_and_fetch_4:
1929 case Builtin::BI__sync_nand_and_fetch_8:
1930 case Builtin::BI__sync_nand_and_fetch_16:
1931 BuiltinIndex = 11;
1932 WarnAboutSemanticsChange = true;
Douglas Gregora9766412011-11-28 16:30:08 +00001933 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattner5caa3702009-05-08 06:58:22 +00001935 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001936 case Builtin::BI__sync_val_compare_and_swap_1:
1937 case Builtin::BI__sync_val_compare_and_swap_2:
1938 case Builtin::BI__sync_val_compare_and_swap_4:
1939 case Builtin::BI__sync_val_compare_and_swap_8:
1940 case Builtin::BI__sync_val_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001941 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +00001942 NumFixed = 2;
1943 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001944
Chris Lattner5caa3702009-05-08 06:58:22 +00001945 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001946 case Builtin::BI__sync_bool_compare_and_swap_1:
1947 case Builtin::BI__sync_bool_compare_and_swap_2:
1948 case Builtin::BI__sync_bool_compare_and_swap_4:
1949 case Builtin::BI__sync_bool_compare_and_swap_8:
1950 case Builtin::BI__sync_bool_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001951 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001952 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001953 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001954 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001955
1956 case Builtin::BI__sync_lock_test_and_set:
1957 case Builtin::BI__sync_lock_test_and_set_1:
1958 case Builtin::BI__sync_lock_test_and_set_2:
1959 case Builtin::BI__sync_lock_test_and_set_4:
1960 case Builtin::BI__sync_lock_test_and_set_8:
1961 case Builtin::BI__sync_lock_test_and_set_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001962 BuiltinIndex = 14;
Douglas Gregora9766412011-11-28 16:30:08 +00001963 break;
1964
Chris Lattner5caa3702009-05-08 06:58:22 +00001965 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001966 case Builtin::BI__sync_lock_release_1:
1967 case Builtin::BI__sync_lock_release_2:
1968 case Builtin::BI__sync_lock_release_4:
1969 case Builtin::BI__sync_lock_release_8:
1970 case Builtin::BI__sync_lock_release_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001971 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +00001972 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001973 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001974 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001975
1976 case Builtin::BI__sync_swap:
1977 case Builtin::BI__sync_swap_1:
1978 case Builtin::BI__sync_swap_2:
1979 case Builtin::BI__sync_swap_4:
1980 case Builtin::BI__sync_swap_8:
1981 case Builtin::BI__sync_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001982 BuiltinIndex = 16;
Douglas Gregora9766412011-11-28 16:30:08 +00001983 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Chris Lattner5caa3702009-05-08 06:58:22 +00001986 // Now that we know how many fixed arguments we expect, first check that we
1987 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001988 if (TheCall->getNumArgs() < 1+NumFixed) {
1989 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1990 << 0 << 1+NumFixed << TheCall->getNumArgs()
1991 << TheCall->getCallee()->getSourceRange();
1992 return ExprError();
1993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Stephen Hines176edba2014-12-01 14:53:08 -08001995 if (WarnAboutSemanticsChange) {
1996 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1997 << TheCall->getCallee()->getSourceRange();
1998 }
1999
Chris Lattnere7ac0a92009-05-08 15:36:58 +00002000 // Get the decl for the concrete builtin from this, we can tell what the
2001 // concrete integer type we should convert to is.
2002 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2003 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00002004 FunctionDecl *NewBuiltinDecl;
2005 if (NewBuiltinID == BuiltinID)
2006 NewBuiltinDecl = FDecl;
2007 else {
2008 // Perform builtin lookup to avoid redeclaring it.
2009 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2010 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2011 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2012 assert(Res.getFoundDecl());
2013 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002014 if (!NewBuiltinDecl)
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00002015 return ExprError();
2016 }
Chandler Carruthd2014572010-07-09 18:59:35 +00002017
John McCallf871d0c2010-08-07 06:22:56 +00002018 // The first argument --- the pointer --- has a fixed type; we
2019 // deduce the types of the rest of the arguments accordingly. Walk
2020 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00002021 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00002022 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Chris Lattner5caa3702009-05-08 06:58:22 +00002024 // GCC does an implicit conversion to the pointer or integer ValType. This
2025 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00002026 // Initialize the argument.
2027 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2028 ValType, /*consume*/ false);
2029 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00002030 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00002031 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Chris Lattner5caa3702009-05-08 06:58:22 +00002033 // Okay, we have something that *can* be converted to the right type. Check
2034 // to see if there is a potentially weird extension going on here. This can
2035 // happen when you do an atomic operation on something like an char* and
2036 // pass in 42. The 42 gets converted to char. This is even more strange
2037 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00002038 // FIXME: Do this check.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002039 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00002042 ASTContext& Context = this->getASTContext();
2043
2044 // Create a new DeclRefExpr to refer to the new decl.
2045 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2046 Context,
2047 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002048 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00002049 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002050 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00002051 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002052 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00002053 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Chris Lattner5caa3702009-05-08 06:58:22 +00002055 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00002056 // FIXME: This loses syntactic information.
2057 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2058 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2059 CK_BuiltinFnToFnPtr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002060 TheCall->setCallee(PromotedCall.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Chandler Carruthdb4325b2010-07-18 07:23:17 +00002062 // Change the result type of the call to match the original value type. This
2063 // is arbitrary, but the codegen for these builtins ins design to handle it
2064 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00002065 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00002066
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002067 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00002068}
2069
Chris Lattner69039812009-02-18 06:01:06 +00002070/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00002071/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00002072/// Note: It might also make sense to do the UTF-16 conversion here (would
2073/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00002074bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00002075 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002076 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2077
Douglas Gregor5cee1192011-07-27 05:40:30 +00002078 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002079 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2080 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00002081 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002084 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002085 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002086 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002087 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00002088 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002089 UTF16 *ToPtr = &ToBuf[0];
2090
2091 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2092 &ToPtr, ToPtr + NumBytes,
2093 strictConversion);
2094 // Check for conversion failure.
2095 if (Result != conversionOK)
2096 Diag(Arg->getLocStart(),
2097 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2098 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00002099 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00002100}
2101
Chris Lattnerc27c6652007-12-20 00:05:45 +00002102/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2103/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00002104bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2105 Expr *Fn = TheCall->getCallee();
2106 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00002107 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002108 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002109 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2110 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00002111 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002112 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00002113 return true;
2114 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00002115
2116 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00002117 return Diag(TheCall->getLocEnd(),
2118 diag::err_typecheck_call_too_few_args_at_least)
2119 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00002120 }
2121
John McCall5f8d6042011-08-27 01:09:30 +00002122 // Type-check the first argument normally.
2123 if (checkBuiltinArgument(*this, TheCall, 0))
2124 return true;
2125
Chris Lattnerc27c6652007-12-20 00:05:45 +00002126 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002127 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00002128 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002129 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00002130 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00002131 else if (FunctionDecl *FD = getCurFunctionDecl())
2132 isVariadic = FD->isVariadic();
2133 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002134 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Chris Lattnerc27c6652007-12-20 00:05:45 +00002136 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00002137 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2138 return true;
2139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Chris Lattner30ce3442007-12-19 23:59:04 +00002141 // Verify that the second argument to the builtin is the last argument of the
2142 // current function or method.
2143 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00002144 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Nico Weberb07d4482013-05-24 23:31:57 +00002146 // These are valid if SecondArgIsLastNamedArgument is false after the next
2147 // block.
2148 QualType Type;
2149 SourceLocation ParamLoc;
2150
Anders Carlsson88cf2262008-02-11 04:20:54 +00002151 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2152 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00002153 // FIXME: This isn't correct for methods (results in bogus warning).
2154 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00002155 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002156 if (CurBlock)
2157 LastArg = *(CurBlock->TheDecl->param_end()-1);
2158 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00002159 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002160 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002161 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002162 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00002163
2164 Type = PV->getType();
2165 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00002166 }
2167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Chris Lattner30ce3442007-12-19 23:59:04 +00002169 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00002170 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00002171 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00002172 else if (Type->isReferenceType()) {
2173 Diag(Arg->getLocStart(),
2174 diag::warn_va_start_of_reference_type_is_undefined);
2175 Diag(ParamLoc, diag::note_parameter_type) << Type;
2176 }
2177
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00002178 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00002179 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00002180}
Chris Lattner30ce3442007-12-19 23:59:04 +00002181
Stephen Hines176edba2014-12-01 14:53:08 -08002182bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2183 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2184 // const char *named_addr);
2185
2186 Expr *Func = Call->getCallee();
2187
2188 if (Call->getNumArgs() < 3)
2189 return Diag(Call->getLocEnd(),
2190 diag::err_typecheck_call_too_few_args_at_least)
2191 << 0 /*function call*/ << 3 << Call->getNumArgs();
2192
2193 // Determine whether the current function is variadic or not.
2194 bool IsVariadic;
2195 if (BlockScopeInfo *CurBlock = getCurBlock())
2196 IsVariadic = CurBlock->TheDecl->isVariadic();
2197 else if (FunctionDecl *FD = getCurFunctionDecl())
2198 IsVariadic = FD->isVariadic();
2199 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2200 IsVariadic = MD->isVariadic();
2201 else
2202 llvm_unreachable("unexpected statement type");
2203
2204 if (!IsVariadic) {
2205 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2206 return true;
2207 }
2208
2209 // Type-check the first argument normally.
2210 if (checkBuiltinArgument(*this, Call, 0))
2211 return true;
2212
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002213 const struct {
Stephen Hines176edba2014-12-01 14:53:08 -08002214 unsigned ArgNo;
2215 QualType Type;
2216 } ArgumentTypes[] = {
2217 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2218 { 2, Context.getSizeType() },
2219 };
2220
2221 for (const auto &AT : ArgumentTypes) {
2222 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2223 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2224 continue;
2225 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2226 << Arg->getType() << AT.Type << 1 /* different class */
2227 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2228 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2229 }
2230
2231 return false;
2232}
2233
Chris Lattner1b9a0792007-12-20 00:26:33 +00002234/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2235/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00002236bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2237 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00002238 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002239 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00002240 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00002241 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002242 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002243 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002244 << SourceRange(TheCall->getArg(2)->getLocStart(),
2245 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002246
John Wiegley429bb272011-04-08 18:41:53 +00002247 ExprResult OrigArg0 = TheCall->getArg(0);
2248 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00002249
Chris Lattner1b9a0792007-12-20 00:26:33 +00002250 // Do standard promotions between the two arguments, returning their common
2251 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00002252 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00002253 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2254 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00002255
2256 // Make sure any conversions are pushed back into the call; this is
2257 // type safe since unordered compare builtins are declared as "_Bool
2258 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00002259 TheCall->setArg(0, OrigArg0.get());
2260 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002261
John Wiegley429bb272011-04-08 18:41:53 +00002262 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00002263 return false;
2264
Chris Lattner1b9a0792007-12-20 00:26:33 +00002265 // If the common type isn't a real floating type, then the arguments were
2266 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00002267 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00002268 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002269 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00002270 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2271 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattner1b9a0792007-12-20 00:26:33 +00002273 return false;
2274}
2275
Benjamin Kramere771a7a2010-02-15 22:42:31 +00002276/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2277/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002278/// to check everything. We expect the last argument to be a floating point
2279/// value.
2280bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2281 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00002282 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002283 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002284 if (TheCall->getNumArgs() > NumArgs)
2285 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002286 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002287 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002288 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002289 (*(TheCall->arg_end()-1))->getLocEnd());
2290
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002291 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Eli Friedman9ac6f622009-08-31 20:06:00 +00002293 if (OrigArg->isTypeDependent())
2294 return false;
2295
Chris Lattner81368fb2010-05-06 05:50:07 +00002296 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00002297 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00002298 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002299 diag::err_typecheck_call_invalid_unary_fp)
2300 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattner81368fb2010-05-06 05:50:07 +00002302 // If this is an implicit conversion from float -> double, remove it.
2303 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2304 Expr *CastArg = Cast->getSubExpr();
2305 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2306 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2307 "promotion from float to double is the only expected cast here");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002308 Cast->setSubExpr(nullptr);
Chris Lattner81368fb2010-05-06 05:50:07 +00002309 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00002310 }
2311 }
2312
Eli Friedman9ac6f622009-08-31 20:06:00 +00002313 return false;
2314}
2315
Eli Friedmand38617c2008-05-14 19:38:39 +00002316/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2317// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00002318ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002319 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002320 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00002321 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00002322 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2323 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002324
Nate Begeman37b6a572010-06-08 00:16:34 +00002325 // Determine which of the following types of shufflevector we're checking:
2326 // 1) unary, vector mask: (lhs, mask)
2327 // 2) binary, vector mask: (lhs, rhs, mask)
2328 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2329 QualType resType = TheCall->getArg(0)->getType();
2330 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00002331
Douglas Gregorcde01732009-05-19 22:10:17 +00002332 if (!TheCall->getArg(0)->isTypeDependent() &&
2333 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002334 QualType LHSType = TheCall->getArg(0)->getType();
2335 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00002336
Craig Topperbbe759c2013-07-29 06:47:04 +00002337 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2338 return ExprError(Diag(TheCall->getLocStart(),
2339 diag::err_shufflevector_non_vector)
2340 << SourceRange(TheCall->getArg(0)->getLocStart(),
2341 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002342
Nate Begeman37b6a572010-06-08 00:16:34 +00002343 numElements = LHSType->getAs<VectorType>()->getNumElements();
2344 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Nate Begeman37b6a572010-06-08 00:16:34 +00002346 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2347 // with mask. If so, verify that RHS is an integer vector type with the
2348 // same number of elts as lhs.
2349 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00002350 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00002351 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00002352 return ExprError(Diag(TheCall->getLocStart(),
2353 diag::err_shufflevector_incompatible_vector)
2354 << SourceRange(TheCall->getArg(1)->getLocStart(),
2355 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002356 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00002357 return ExprError(Diag(TheCall->getLocStart(),
2358 diag::err_shufflevector_incompatible_vector)
2359 << SourceRange(TheCall->getArg(0)->getLocStart(),
2360 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00002361 } else if (numElements != numResElements) {
2362 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00002363 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002364 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00002365 }
Eli Friedmand38617c2008-05-14 19:38:39 +00002366 }
2367
2368 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00002369 if (TheCall->getArg(i)->isTypeDependent() ||
2370 TheCall->getArg(i)->isValueDependent())
2371 continue;
2372
Nate Begeman37b6a572010-06-08 00:16:34 +00002373 llvm::APSInt Result(32);
2374 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2375 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002376 diag::err_shufflevector_nonconstant_argument)
2377 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002378
Craig Topper6f4f8082013-08-03 17:40:38 +00002379 // Allow -1 which will be translated to undef in the IR.
2380 if (Result.isSigned() && Result.isAllOnesValue())
2381 continue;
2382
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002383 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002384 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002385 diag::err_shufflevector_argument_too_large)
2386 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002387 }
2388
Chris Lattner5f9e2722011-07-23 10:55:15 +00002389 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00002390
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002391 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00002392 exprs.push_back(TheCall->getArg(i));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002393 TheCall->setArg(i, nullptr);
Eli Friedmand38617c2008-05-14 19:38:39 +00002394 }
2395
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002396 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2397 TheCall->getCallee()->getLocStart(),
2398 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +00002399}
Chris Lattner30ce3442007-12-19 23:59:04 +00002400
Hal Finkel414a1bd2013-09-18 03:29:45 +00002401/// SemaConvertVectorExpr - Handle __builtin_convertvector
2402ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2403 SourceLocation BuiltinLoc,
2404 SourceLocation RParenLoc) {
2405 ExprValueKind VK = VK_RValue;
2406 ExprObjectKind OK = OK_Ordinary;
2407 QualType DstTy = TInfo->getType();
2408 QualType SrcTy = E->getType();
2409
2410 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2411 return ExprError(Diag(BuiltinLoc,
2412 diag::err_convertvector_non_vector)
2413 << E->getSourceRange());
2414 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2415 return ExprError(Diag(BuiltinLoc,
2416 diag::err_convertvector_non_vector_type));
2417
2418 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2419 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2420 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2421 if (SrcElts != DstElts)
2422 return ExprError(Diag(BuiltinLoc,
2423 diag::err_convertvector_incompatible_vector)
2424 << E->getSourceRange());
2425 }
2426
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002427 return new (Context)
2428 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkel414a1bd2013-09-18 03:29:45 +00002429}
2430
Daniel Dunbar4493f792008-07-21 22:59:13 +00002431/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2432// This is declared to take (const void*, ...) and can take two
2433// optional constant int args.
2434bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002435 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002436
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002437 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00002438 return Diag(TheCall->getLocEnd(),
2439 diag::err_typecheck_call_too_many_args_at_most)
2440 << 0 /*function call*/ << 3 << NumArgs
2441 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002442
2443 // Argument 0 is checked for us and the remaining arguments must be
2444 // constant integers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002445 for (unsigned i = 1; i != NumArgs; ++i)
2446 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher691ebc32010-04-17 02:26:23 +00002447 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Stephen Hines651f13c2014-04-23 16:59:28 -07002449 return false;
2450}
2451
Stephen Hines176edba2014-12-01 14:53:08 -08002452/// SemaBuiltinAssume - Handle __assume (MS Extension).
2453// __assume does not evaluate its arguments, and should warn if its argument
2454// has side effects.
2455bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2456 Expr *Arg = TheCall->getArg(0);
2457 if (Arg->isInstantiationDependent()) return false;
2458
2459 if (Arg->HasSideEffects(Context))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002460 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Stephen Hines176edba2014-12-01 14:53:08 -08002461 << Arg->getSourceRange()
2462 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2463
2464 return false;
2465}
2466
2467/// Handle __builtin_assume_aligned. This is declared
2468/// as (const void*, size_t, ...) and can take one optional constant int arg.
2469bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2470 unsigned NumArgs = TheCall->getNumArgs();
2471
2472 if (NumArgs > 3)
2473 return Diag(TheCall->getLocEnd(),
2474 diag::err_typecheck_call_too_many_args_at_most)
2475 << 0 /*function call*/ << 3 << NumArgs
2476 << TheCall->getSourceRange();
2477
2478 // The alignment must be a constant integer.
2479 Expr *Arg = TheCall->getArg(1);
2480
2481 // We can't check the value of a dependent argument.
2482 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2483 llvm::APSInt Result;
2484 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2485 return true;
2486
2487 if (!Result.isPowerOf2())
2488 return Diag(TheCall->getLocStart(),
2489 diag::err_alignment_not_power_of_two)
2490 << Arg->getSourceRange();
2491 }
2492
2493 if (NumArgs > 2) {
2494 ExprResult Arg(TheCall->getArg(2));
2495 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2496 Context.getSizeType(), false);
2497 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2498 if (Arg.isInvalid()) return true;
2499 TheCall->setArg(2, Arg.get());
2500 }
2501
2502 return false;
2503}
2504
Eric Christopher691ebc32010-04-17 02:26:23 +00002505/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2506/// TheCall is a constant expression.
2507bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2508 llvm::APSInt &Result) {
2509 Expr *Arg = TheCall->getArg(ArgNum);
2510 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2511 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2512
2513 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2514
2515 if (!Arg->isIntegerConstantExpr(Result, Context))
2516 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00002517 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00002518
Chris Lattner21fb98e2009-09-23 06:06:36 +00002519 return false;
2520}
2521
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002522/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2523/// TheCall is a constant expression in the range [Low, High].
2524bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2525 int Low, int High) {
Eric Christopher691ebc32010-04-17 02:26:23 +00002526 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00002527
2528 // We can't check the value of a dependent argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002529 Expr *Arg = TheCall->getArg(ArgNum);
2530 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor592a4232012-06-29 01:05:22 +00002531 return false;
2532
Eric Christopher691ebc32010-04-17 02:26:23 +00002533 // Check constant-ness first.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002534 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher691ebc32010-04-17 02:26:23 +00002535 return true;
2536
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002537 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002538 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002539 << Low << High << Arg->getSourceRange();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002540
2541 return false;
2542}
2543
Eli Friedman586d6a82009-05-03 06:04:26 +00002544/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002545/// This checks that the target supports __builtin_longjmp and
2546/// that val is a constant 1.
Eli Friedmand875fed2009-05-03 04:46:36 +00002547bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002548 if (!Context.getTargetInfo().hasSjLjLowering())
2549 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2550 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2551
Eli Friedmand875fed2009-05-03 04:46:36 +00002552 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00002553 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00002554
Eric Christopher691ebc32010-04-17 02:26:23 +00002555 // TODO: This is less than ideal. Overload this to take a value.
2556 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2557 return true;
2558
2559 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00002560 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2561 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2562
2563 return false;
2564}
2565
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002566
2567/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2568/// This checks that the target supports __builtin_setjmp.
2569bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2570 if (!Context.getTargetInfo().hasSjLjLowering())
2571 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2572 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2573 return false;
2574}
2575
Richard Smith0e218972013-08-05 18:49:43 +00002576namespace {
2577enum StringLiteralCheckType {
2578 SLCT_NotALiteral,
2579 SLCT_UncheckedLiteral,
2580 SLCT_CheckedLiteral
2581};
2582}
2583
Richard Smith831421f2012-06-25 20:30:08 +00002584// Determine if an expression is a string literal or constant string.
2585// If this function returns false on the arguments to a function expecting a
2586// format string, we will usually need to emit a warning.
2587// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00002588static StringLiteralCheckType
2589checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2590 bool HasVAListArg, unsigned format_idx,
2591 unsigned firstDataArg, Sema::FormatStringType Type,
2592 Sema::VariadicCallType CallType, bool InFunctionCall,
2593 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002594 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00002595 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00002596 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002597
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002598 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002599
Richard Smith0e218972013-08-05 18:49:43 +00002600 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00002601 // Technically -Wformat-nonliteral does not warn about this case.
2602 // The behavior of printf and friends in this case is implementation
2603 // dependent. Ideally if the format string cannot be null then
2604 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00002605 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002606
Ted Kremenekd30ef872009-01-12 23:09:09 +00002607 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002608 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002609 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00002610 // The expression is a literal if both sub-expressions were, and it was
2611 // completely checked only if both sub-expressions were checked.
2612 const AbstractConditionalOperator *C =
2613 cast<AbstractConditionalOperator>(E);
2614 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002615 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002616 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002617 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002618 if (Left == SLCT_NotALiteral)
2619 return SLCT_NotALiteral;
2620 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002621 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002622 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002623 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002624 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002625 }
2626
2627 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002628 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2629 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002630 }
2631
John McCall56ca35d2011-02-17 10:25:35 +00002632 case Stmt::OpaqueValueExprClass:
2633 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2634 E = src;
2635 goto tryAgain;
2636 }
Richard Smith831421f2012-06-25 20:30:08 +00002637 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002638
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002639 case Stmt::PredefinedExprClass:
2640 // While __func__, etc., are technically not string literals, they
2641 // cannot contain format specifiers and thus are not a security
2642 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002643 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002644
Ted Kremenek082d9362009-03-20 21:35:28 +00002645 case Stmt::DeclRefExprClass: {
2646 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Ted Kremenek082d9362009-03-20 21:35:28 +00002648 // As an exception, do not flag errors for variables binding to
2649 // const string literals.
2650 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2651 bool isConstant = false;
2652 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002653
Richard Smith0e218972013-08-05 18:49:43 +00002654 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2655 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002656 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002657 isConstant = T.isConstant(S.Context) &&
2658 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002659 } else if (T->isObjCObjectPointerType()) {
2660 // In ObjC, there is usually no "const ObjectPointer" type,
2661 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002662 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002663 }
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Ted Kremenek082d9362009-03-20 21:35:28 +00002665 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002666 if (const Expr *Init = VD->getAnyInitializer()) {
2667 // Look through initializers like const char c[] = { "foo" }
2668 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2669 if (InitList->isStringLiteralInit())
2670 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2671 }
Richard Smith0e218972013-08-05 18:49:43 +00002672 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002673 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002674 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002675 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002676 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002677 }
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Anders Carlssond966a552009-06-28 19:55:58 +00002679 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2680 // special check to see if the format string is a function parameter
2681 // of the function calling the printf function. If the function
2682 // has an attribute indicating it is a printf-like function, then we
2683 // should suppress warnings concerning non-literals being used in a call
2684 // to a vprintf function. For example:
2685 //
2686 // void
2687 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2688 // va_list ap;
2689 // va_start(ap, fmt);
2690 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2691 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002692 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002693 if (HasVAListArg) {
2694 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2695 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2696 int PVIndex = PV->getFunctionScopeIndex() + 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002697 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002698 // adjust for implicit parameter
2699 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2700 if (MD->isInstance())
2701 ++PVIndex;
2702 // We also check if the formats are compatible.
2703 // We can't pass a 'scanf' string to a 'printf' function.
2704 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002705 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002706 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002707 }
2708 }
2709 }
2710 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002711 }
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Richard Smith831421f2012-06-25 20:30:08 +00002713 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002714 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002715
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002716 case Stmt::CallExprClass:
2717 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002718 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002719 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2720 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2721 unsigned ArgIndex = FA->getFormatIdx();
2722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2723 if (MD->isInstance())
2724 --ArgIndex;
2725 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Richard Smith0e218972013-08-05 18:49:43 +00002727 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002728 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002729 Type, CallType, InFunctionCall,
2730 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002731 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2732 unsigned BuiltinID = FD->getBuiltinID();
2733 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2734 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2735 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002736 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002737 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002738 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002739 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002740 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002741 }
2742 }
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Richard Smith831421f2012-06-25 20:30:08 +00002744 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002745 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002746 case Stmt::ObjCStringLiteralClass:
2747 case Stmt::StringLiteralClass: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002748 const StringLiteral *StrE = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Ted Kremenek082d9362009-03-20 21:35:28 +00002750 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002751 StrE = ObjCFExpr->getString();
2752 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002753 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Ted Kremenekd30ef872009-01-12 23:09:09 +00002755 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002756 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2757 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002758 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002759 }
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Richard Smith831421f2012-06-25 20:30:08 +00002761 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Ted Kremenek082d9362009-03-20 21:35:28 +00002764 default:
Richard Smith831421f2012-06-25 20:30:08 +00002765 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002766 }
2767}
2768
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002769Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002770 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002771 .Case("scanf", FST_Scanf)
2772 .Cases("printf", "printf0", FST_Printf)
2773 .Cases("NSString", "CFString", FST_NSString)
2774 .Case("strftime", FST_Strftime)
2775 .Case("strfmon", FST_Strfmon)
2776 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002777 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2778 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002779 .Default(FST_Unknown);
2780}
2781
Jordan Roseddcfbc92012-07-19 18:10:23 +00002782/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002783/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002784/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002785bool Sema::CheckFormatArguments(const FormatAttr *Format,
2786 ArrayRef<const Expr *> Args,
2787 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002788 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002789 SourceLocation Loc, SourceRange Range,
2790 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002791 FormatStringInfo FSI;
2792 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002793 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002794 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002795 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002796 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002797}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002798
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002799bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002800 bool HasVAListArg, unsigned format_idx,
2801 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002802 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002803 SourceLocation Loc, SourceRange Range,
2804 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002805 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002806 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002807 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002808 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002811 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Chris Lattner59907c42007-08-10 20:18:51 +00002813 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002814 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002815 // Dynamically generated format strings are difficult to
2816 // automatically vet at compile time. Requiring that format strings
2817 // are string literals: (1) permits the checking of format strings by
2818 // the compiler and thereby (2) can practically remove the source of
2819 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002820
Mike Stump1eb44332009-09-09 15:08:12 +00002821 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002822 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002823 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002824 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002825 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002826 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2827 format_idx, firstDataArg, Type, CallType,
2828 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002829 if (CT != SLCT_NotALiteral)
2830 // Literal format string found, check done!
2831 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002832
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002833 // Strftime is particular as it always uses a single 'time' argument,
2834 // so it is safe to pass a non-literal string.
2835 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002836 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002837
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002838 // Do not emit diag when the string param is a macro expansion and the
2839 // format is either NSString or CFString. This is a hack to prevent
2840 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2841 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002842 if (Type == FST_NSString &&
2843 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002844 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002845
Chris Lattner655f1412009-04-29 04:59:47 +00002846 // If there are no arguments specified, warn with -Wformat-security, otherwise
2847 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002848 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002849 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002850 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002851 << OrigFormatExpr->getSourceRange();
2852 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002853 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002854 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002855 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002856 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002857}
Ted Kremenek71895b92007-08-14 17:39:48 +00002858
Ted Kremeneke0e53132010-01-28 23:39:18 +00002859namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002860class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2861protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002862 Sema &S;
2863 const StringLiteral *FExpr;
2864 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002865 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002866 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002867 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002868 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002869 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002870 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002871 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002872 bool usesPositionalArgs;
2873 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002874 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002875 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002876 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002877public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002878 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002879 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002880 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002881 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002882 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002883 Sema::VariadicCallType callType,
2884 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002885 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002886 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2887 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002888 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002889 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002890 inFunctionCall(inFunctionCall), CallType(callType),
2891 CheckedVarArgs(CheckedVarArgs) {
2892 CoveredArgs.resize(numDataArgs);
2893 CoveredArgs.reset();
2894 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002895
Ted Kremenek07d161f2010-01-29 01:50:07 +00002896 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002897
Ted Kremenek826a3452010-07-16 02:11:22 +00002898 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002899 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002900
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002901 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002902 const analyze_format_string::FormatSpecifier &FS,
2903 const analyze_format_string::ConversionSpecifier &CS,
2904 const char *startSpecifier, unsigned specifierLen,
2905 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002906
Hans Wennborg76517422012-02-22 10:17:01 +00002907 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002908 const analyze_format_string::FormatSpecifier &FS,
2909 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002910
2911 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002912 const analyze_format_string::ConversionSpecifier &CS,
2913 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002914
Stephen Hines651f13c2014-04-23 16:59:28 -07002915 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002916
Stephen Hines651f13c2014-04-23 16:59:28 -07002917 void HandleInvalidPosition(const char *startSpecifier,
2918 unsigned specifierLen,
2919 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002920
Stephen Hines651f13c2014-04-23 16:59:28 -07002921 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002922
Stephen Hines651f13c2014-04-23 16:59:28 -07002923 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002924
Richard Trieu55733de2011-10-28 00:41:25 +00002925 template <typename Range>
2926 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2927 const Expr *ArgumentExpr,
2928 PartialDiagnostic PDiag,
2929 SourceLocation StringLoc,
2930 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002931 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002932
Ted Kremenek826a3452010-07-16 02:11:22 +00002933protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002934 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2935 const char *startSpec,
2936 unsigned specifierLen,
2937 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002938
2939 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2940 const char *startSpec,
2941 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002942
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002943 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002944 CharSourceRange getSpecifierRange(const char *startSpecifier,
2945 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002946 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002947
Ted Kremenek0d277352010-01-29 01:06:55 +00002948 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002949
2950 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2951 const analyze_format_string::ConversionSpecifier &CS,
2952 const char *startSpecifier, unsigned specifierLen,
2953 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002954
2955 template <typename Range>
2956 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2957 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002958 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002959};
2960}
2961
Ted Kremenek826a3452010-07-16 02:11:22 +00002962SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002963 return OrigFormatExpr->getSourceRange();
2964}
2965
Ted Kremenek826a3452010-07-16 02:11:22 +00002966CharSourceRange CheckFormatHandler::
2967getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002968 SourceLocation Start = getLocationOfByte(startSpecifier);
2969 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2970
2971 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002972 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002973
2974 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002975}
2976
Ted Kremenek826a3452010-07-16 02:11:22 +00002977SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002978 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002979}
2980
Ted Kremenek826a3452010-07-16 02:11:22 +00002981void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2982 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002983 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2984 getLocationOfByte(startSpecifier),
2985 /*IsStringLocation*/true,
2986 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002987}
2988
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002989void CheckFormatHandler::HandleInvalidLengthModifier(
2990 const analyze_format_string::FormatSpecifier &FS,
2991 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002992 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002993 using namespace analyze_format_string;
2994
2995 const LengthModifier &LM = FS.getLengthModifier();
2996 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2997
2998 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002999 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003000 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00003001 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003002 getLocationOfByte(LM.getStart()),
3003 /*IsStringLocation*/true,
3004 getSpecifierRange(startSpecifier, specifierLen));
3005
3006 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3007 << FixedLM->toString()
3008 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3009
3010 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00003011 FixItHint Hint;
3012 if (DiagID == diag::warn_format_nonsensical_length)
3013 Hint = FixItHint::CreateRemoval(LMRange);
3014
3015 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003016 getLocationOfByte(LM.getStart()),
3017 /*IsStringLocation*/true,
3018 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00003019 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003020 }
3021}
3022
Hans Wennborg76517422012-02-22 10:17:01 +00003023void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00003024 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00003025 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00003026 using namespace analyze_format_string;
3027
3028 const LengthModifier &LM = FS.getLengthModifier();
3029 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3030
3031 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00003032 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00003033 if (FixedLM) {
3034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3035 << LM.toString() << 0,
3036 getLocationOfByte(LM.getStart()),
3037 /*IsStringLocation*/true,
3038 getSpecifierRange(startSpecifier, specifierLen));
3039
3040 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3041 << FixedLM->toString()
3042 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3043
3044 } else {
3045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3046 << LM.toString() << 0,
3047 getLocationOfByte(LM.getStart()),
3048 /*IsStringLocation*/true,
3049 getSpecifierRange(startSpecifier, specifierLen));
3050 }
Hans Wennborg76517422012-02-22 10:17:01 +00003051}
3052
3053void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3054 const analyze_format_string::ConversionSpecifier &CS,
3055 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00003056 using namespace analyze_format_string;
3057
3058 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00003059 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00003060 if (FixedCS) {
3061 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3062 << CS.toString() << /*conversion specifier*/1,
3063 getLocationOfByte(CS.getStart()),
3064 /*IsStringLocation*/true,
3065 getSpecifierRange(startSpecifier, specifierLen));
3066
3067 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3068 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3069 << FixedCS->toString()
3070 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3071 } else {
3072 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3073 << CS.toString() << /*conversion specifier*/1,
3074 getLocationOfByte(CS.getStart()),
3075 /*IsStringLocation*/true,
3076 getSpecifierRange(startSpecifier, specifierLen));
3077 }
Hans Wennborg76517422012-02-22 10:17:01 +00003078}
3079
Hans Wennborgf8562642012-03-09 10:10:54 +00003080void CheckFormatHandler::HandlePosition(const char *startPos,
3081 unsigned posLen) {
3082 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3083 getLocationOfByte(startPos),
3084 /*IsStringLocation*/true,
3085 getSpecifierRange(startPos, posLen));
3086}
3087
Ted Kremenekefaff192010-02-27 01:41:03 +00003088void
Ted Kremenek826a3452010-07-16 02:11:22 +00003089CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3090 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00003091 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3092 << (unsigned) p,
3093 getLocationOfByte(startPos), /*IsStringLocation*/true,
3094 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00003095}
3096
Ted Kremenek826a3452010-07-16 02:11:22 +00003097void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00003098 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00003099 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3100 getLocationOfByte(startPos),
3101 /*IsStringLocation*/true,
3102 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00003103}
3104
Ted Kremenek826a3452010-07-16 02:11:22 +00003105void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00003106 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00003107 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00003108 EmitFormatDiagnostic(
3109 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3110 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3111 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00003112 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003113}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003114
Jordan Rose48716662012-07-19 18:10:08 +00003115// Note that this may return NULL if there was an error parsing or building
3116// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00003117const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003118 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00003119}
3120
3121void CheckFormatHandler::DoneProcessing() {
3122 // Does the number of data arguments exceed the number of
3123 // format conversions in the format string?
3124 if (!HasVAListArg) {
3125 // Find any arguments that weren't covered.
3126 CoveredArgs.flip();
3127 signed notCoveredArg = CoveredArgs.find_first();
3128 if (notCoveredArg >= 0) {
3129 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00003130 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3131 SourceLocation Loc = E->getLocStart();
3132 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3133 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3134 Loc, /*IsStringLocation*/false,
3135 getFormatStringRange());
3136 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00003137 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003138 }
3139 }
3140}
3141
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003142bool
3143CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3144 SourceLocation Loc,
3145 const char *startSpec,
3146 unsigned specifierLen,
3147 const char *csStart,
3148 unsigned csLen) {
3149
3150 bool keepGoing = true;
3151 if (argIndex < NumDataArgs) {
3152 // Consider the argument coverered, even though the specifier doesn't
3153 // make sense.
3154 CoveredArgs.set(argIndex);
3155 }
3156 else {
3157 // If argIndex exceeds the number of data arguments we
3158 // don't issue a warning because that is just a cascade of warnings (and
3159 // they may have intended '%%' anyway). We don't want to continue processing
3160 // the format string after this point, however, as we will like just get
3161 // gibberish when trying to match arguments.
3162 keepGoing = false;
3163 }
3164
Richard Trieu55733de2011-10-28 00:41:25 +00003165 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3166 << StringRef(csStart, csLen),
3167 Loc, /*IsStringLocation*/true,
3168 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003169
3170 return keepGoing;
3171}
3172
Richard Trieu55733de2011-10-28 00:41:25 +00003173void
3174CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3175 const char *startSpec,
3176 unsigned specifierLen) {
3177 EmitFormatDiagnostic(
3178 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3179 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3180}
3181
Ted Kremenek666a1972010-07-26 19:45:42 +00003182bool
3183CheckFormatHandler::CheckNumArgs(
3184 const analyze_format_string::FormatSpecifier &FS,
3185 const analyze_format_string::ConversionSpecifier &CS,
3186 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3187
3188 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00003189 PartialDiagnostic PDiag = FS.usesPositionalArg()
3190 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3191 << (argIndex+1) << NumDataArgs)
3192 : S.PDiag(diag::warn_printf_insufficient_data_args);
3193 EmitFormatDiagnostic(
3194 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3195 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00003196 return false;
3197 }
3198 return true;
3199}
3200
Richard Trieu55733de2011-10-28 00:41:25 +00003201template<typename Range>
3202void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3203 SourceLocation Loc,
3204 bool IsStringLocation,
3205 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00003206 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003207 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00003208 Loc, IsStringLocation, StringRange, FixIt);
3209}
3210
3211/// \brief If the format string is not within the funcion call, emit a note
3212/// so that the function call and string are in diagnostic messages.
3213///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00003214/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00003215/// call and only one diagnostic message will be produced. Otherwise, an
3216/// extra note will be emitted pointing to location of the format string.
3217///
3218/// \param ArgumentExpr the expression that is passed as the format string
3219/// argument in the function call. Used for getting locations when two
3220/// diagnostics are emitted.
3221///
3222/// \param PDiag the callee should already have provided any strings for the
3223/// diagnostic message. This function only adds locations and fixits
3224/// to diagnostics.
3225///
3226/// \param Loc primary location for diagnostic. If two diagnostics are
3227/// required, one will be at Loc and a new SourceLocation will be created for
3228/// the other one.
3229///
3230/// \param IsStringLocation if true, Loc points to the format string should be
3231/// used for the note. Otherwise, Loc points to the argument list and will
3232/// be used with PDiag.
3233///
3234/// \param StringRange some or all of the string to highlight. This is
3235/// templated so it can accept either a CharSourceRange or a SourceRange.
3236///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00003237/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00003238template<typename Range>
3239void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3240 const Expr *ArgumentExpr,
3241 PartialDiagnostic PDiag,
3242 SourceLocation Loc,
3243 bool IsStringLocation,
3244 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00003245 ArrayRef<FixItHint> FixIt) {
3246 if (InFunctionCall) {
3247 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3248 D << StringRange;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003249 D << FixIt;
Jordan Roseec087352012-09-05 22:56:26 +00003250 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00003251 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3252 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00003253
3254 const Sema::SemaDiagnosticBuilder &Note =
3255 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3256 diag::note_format_string_defined);
3257
3258 Note << StringRange;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003259 Note << FixIt;
Richard Trieu55733de2011-10-28 00:41:25 +00003260 }
3261}
3262
Ted Kremenek826a3452010-07-16 02:11:22 +00003263//===--- CHECK: Printf format string checking ------------------------------===//
3264
3265namespace {
3266class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00003267 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00003268public:
3269 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3270 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003271 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00003272 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003273 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003274 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003275 Sema::VariadicCallType CallType,
3276 llvm::SmallBitVector &CheckedVarArgs)
3277 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3278 numDataArgs, beg, hasVAListArg, Args,
3279 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3280 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003281 {}
3282
Stephen Hines651f13c2014-04-23 16:59:28 -07003283
Ted Kremenek826a3452010-07-16 02:11:22 +00003284 bool HandleInvalidPrintfConversionSpecifier(
3285 const analyze_printf::PrintfSpecifier &FS,
3286 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003287 unsigned specifierLen) override;
3288
Ted Kremenek826a3452010-07-16 02:11:22 +00003289 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3290 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003291 unsigned specifierLen) override;
Richard Smith831421f2012-06-25 20:30:08 +00003292 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3293 const char *StartSpecifier,
3294 unsigned SpecifierLen,
3295 const Expr *E);
3296
Ted Kremenek826a3452010-07-16 02:11:22 +00003297 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3298 const char *startSpecifier, unsigned specifierLen);
3299 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3300 const analyze_printf::OptionalAmount &Amt,
3301 unsigned type,
3302 const char *startSpecifier, unsigned specifierLen);
3303 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3304 const analyze_printf::OptionalFlag &flag,
3305 const char *startSpecifier, unsigned specifierLen);
3306 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3307 const analyze_printf::OptionalFlag &ignoredFlag,
3308 const analyze_printf::OptionalFlag &flag,
3309 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00003310 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07003311 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00003312
Ted Kremenek826a3452010-07-16 02:11:22 +00003313};
3314}
3315
3316bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3317 const analyze_printf::PrintfSpecifier &FS,
3318 const char *startSpecifier,
3319 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003320 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003321 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003322
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003323 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3324 getLocationOfByte(CS.getStart()),
3325 startSpecifier, specifierLen,
3326 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00003327}
3328
Ted Kremenek826a3452010-07-16 02:11:22 +00003329bool CheckPrintfHandler::HandleAmount(
3330 const analyze_format_string::OptionalAmount &Amt,
3331 unsigned k, const char *startSpecifier,
3332 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003333
3334 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003335 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003336 unsigned argIndex = Amt.getArgIndex();
3337 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00003338 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3339 << k,
3340 getLocationOfByte(Amt.getStart()),
3341 /*IsStringLocation*/true,
3342 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003343 // Don't do any more checking. We will just emit
3344 // spurious errors.
3345 return false;
3346 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003347
Ted Kremenek0d277352010-01-29 01:06:55 +00003348 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00003349 // Although not in conformance with C99, we also allow the argument to be
3350 // an 'unsigned int' as that is a reasonably safe case. GCC also
3351 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003352 CoveredArgs.set(argIndex);
3353 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003354 if (!Arg)
3355 return false;
3356
Ted Kremenek0d277352010-01-29 01:06:55 +00003357 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003358
Hans Wennborgf3749f42012-08-07 08:11:26 +00003359 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3360 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003361
Hans Wennborgf3749f42012-08-07 08:11:26 +00003362 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00003363 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00003364 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00003365 << T << Arg->getSourceRange(),
3366 getLocationOfByte(Amt.getStart()),
3367 /*IsStringLocation*/true,
3368 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003369 // Don't do any more checking. We will just emit
3370 // spurious errors.
3371 return false;
3372 }
3373 }
3374 }
3375 return true;
3376}
Ted Kremenek0d277352010-01-29 01:06:55 +00003377
Tom Caree4ee9662010-06-17 19:00:27 +00003378void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00003379 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003380 const analyze_printf::OptionalAmount &Amt,
3381 unsigned type,
3382 const char *startSpecifier,
3383 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003384 const analyze_printf::PrintfConversionSpecifier &CS =
3385 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00003386
Richard Trieu55733de2011-10-28 00:41:25 +00003387 FixItHint fixit =
3388 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3389 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3390 Amt.getConstantLength()))
3391 : FixItHint();
3392
3393 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3394 << type << CS.toString(),
3395 getLocationOfByte(Amt.getStart()),
3396 /*IsStringLocation*/true,
3397 getSpecifierRange(startSpecifier, specifierLen),
3398 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00003399}
3400
Ted Kremenek826a3452010-07-16 02:11:22 +00003401void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003402 const analyze_printf::OptionalFlag &flag,
3403 const char *startSpecifier,
3404 unsigned specifierLen) {
3405 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003406 const analyze_printf::PrintfConversionSpecifier &CS =
3407 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00003408 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3409 << flag.toString() << CS.toString(),
3410 getLocationOfByte(flag.getPosition()),
3411 /*IsStringLocation*/true,
3412 getSpecifierRange(startSpecifier, specifierLen),
3413 FixItHint::CreateRemoval(
3414 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003415}
3416
3417void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00003418 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003419 const analyze_printf::OptionalFlag &ignoredFlag,
3420 const analyze_printf::OptionalFlag &flag,
3421 const char *startSpecifier,
3422 unsigned specifierLen) {
3423 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00003424 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3425 << ignoredFlag.toString() << flag.toString(),
3426 getLocationOfByte(ignoredFlag.getPosition()),
3427 /*IsStringLocation*/true,
3428 getSpecifierRange(startSpecifier, specifierLen),
3429 FixItHint::CreateRemoval(
3430 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003431}
3432
Richard Smith831421f2012-06-25 20:30:08 +00003433// Determines if the specified is a C++ class or struct containing
3434// a member with the specified name and kind (e.g. a CXXMethodDecl named
3435// "c_str()").
3436template<typename MemberKind>
3437static llvm::SmallPtrSet<MemberKind*, 1>
3438CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3439 const RecordType *RT = Ty->getAs<RecordType>();
3440 llvm::SmallPtrSet<MemberKind*, 1> Results;
3441
3442 if (!RT)
3443 return Results;
3444 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07003445 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00003446 return Results;
3447
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003448 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith831421f2012-06-25 20:30:08 +00003449 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07003450 R.suppressDiagnostics();
Richard Smith831421f2012-06-25 20:30:08 +00003451
3452 // We just need to include all members of the right kind turned up by the
3453 // filter, at this point.
3454 if (S.LookupQualifiedName(R, RT->getDecl()))
3455 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3456 NamedDecl *decl = (*I)->getUnderlyingDecl();
3457 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3458 Results.insert(FK);
3459 }
3460 return Results;
3461}
3462
Stephen Hines651f13c2014-04-23 16:59:28 -07003463/// Check if we could call '.c_str()' on an object.
3464///
3465/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3466/// allow the call, or if it would be ambiguous).
3467bool Sema::hasCStrMethod(const Expr *E) {
3468 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3469 MethodSet Results =
3470 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3471 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3472 MI != ME; ++MI)
3473 if ((*MI)->getMinRequiredArguments() == 0)
3474 return true;
3475 return false;
3476}
3477
Richard Smith831421f2012-06-25 20:30:08 +00003478// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00003479// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00003480// Returns true when a c_str() conversion method is found.
3481bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07003482 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-06-25 20:30:08 +00003483 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3484
3485 MethodSet Results =
3486 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3487
3488 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3489 MI != ME; ++MI) {
3490 const CXXMethodDecl *Method = *MI;
Stephen Hines651f13c2014-04-23 16:59:28 -07003491 if (Method->getMinRequiredArguments() == 0 &&
3492 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00003493 // FIXME: Suggest parens if the expression needs them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003494 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith831421f2012-06-25 20:30:08 +00003495 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3496 << "c_str()"
3497 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3498 return true;
3499 }
3500 }
3501
3502 return false;
3503}
3504
Ted Kremeneke0e53132010-01-28 23:39:18 +00003505bool
Ted Kremenek826a3452010-07-16 02:11:22 +00003506CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00003507 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00003508 const char *startSpecifier,
3509 unsigned specifierLen) {
3510
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003511 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00003512 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003513 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00003514
Ted Kremenekbaa40062010-07-19 22:01:06 +00003515 if (FS.consumesDataArgument()) {
3516 if (atFirstArg) {
3517 atFirstArg = false;
3518 usesPositionalArgs = FS.usesPositionalArg();
3519 }
3520 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003521 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3522 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003523 return false;
3524 }
Ted Kremenek0d277352010-01-29 01:06:55 +00003525 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003526
Ted Kremenekefaff192010-02-27 01:41:03 +00003527 // First check if the field width, precision, and conversion specifier
3528 // have matching data arguments.
3529 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3530 startSpecifier, specifierLen)) {
3531 return false;
3532 }
3533
3534 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3535 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003536 return false;
3537 }
3538
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003539 if (!CS.consumesDataArgument()) {
3540 // FIXME: Technically specifying a precision or field width here
3541 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003542 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003543 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003544
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003545 // Consume the argument.
3546 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00003547 if (argIndex < NumDataArgs) {
3548 // The check to see if the argIndex is valid will come later.
3549 // We set the bit here because we may exit early from this
3550 // function if we encounter some other error.
3551 CoveredArgs.set(argIndex);
3552 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003553
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003554 // FreeBSD kernel extensions.
3555 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3556 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3557 // We need at least two arguments.
3558 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3559 return false;
3560
3561 // Claim the second argument.
3562 CoveredArgs.set(argIndex + 1);
3563
3564 // Type check the first argument (int for %b, pointer for %D)
3565 const Expr *Ex = getDataArg(argIndex);
3566 const analyze_printf::ArgType &AT =
3567 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3568 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3569 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3570 EmitFormatDiagnostic(
3571 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3572 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3573 << false << Ex->getSourceRange(),
3574 Ex->getLocStart(), /*IsStringLocation*/false,
3575 getSpecifierRange(startSpecifier, specifierLen));
3576
3577 // Type check the second argument (char * for both %b and %D)
3578 Ex = getDataArg(argIndex + 1);
3579 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3580 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3581 EmitFormatDiagnostic(
3582 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3583 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3584 << false << Ex->getSourceRange(),
3585 Ex->getLocStart(), /*IsStringLocation*/false,
3586 getSpecifierRange(startSpecifier, specifierLen));
3587
3588 return true;
3589 }
3590
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003591 // Check for using an Objective-C specific conversion specifier
3592 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00003593 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003594 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3595 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003596 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003597
Tom Caree4ee9662010-06-17 19:00:27 +00003598 // Check for invalid use of field width
3599 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00003600 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00003601 startSpecifier, specifierLen);
3602 }
3603
3604 // Check for invalid use of precision
3605 if (!FS.hasValidPrecision()) {
3606 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3607 startSpecifier, specifierLen);
3608 }
3609
3610 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00003611 if (!FS.hasValidThousandsGroupingPrefix())
3612 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003613 if (!FS.hasValidLeadingZeros())
3614 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3615 if (!FS.hasValidPlusPrefix())
3616 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003617 if (!FS.hasValidSpacePrefix())
3618 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003619 if (!FS.hasValidAlternativeForm())
3620 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3621 if (!FS.hasValidLeftJustified())
3622 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3623
3624 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003625 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3626 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3627 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003628 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3629 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3630 startSpecifier, specifierLen);
3631
3632 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003633 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003634 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3635 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003636 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003637 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003638 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003639 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3640 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003641
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003642 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3643 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3644
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003645 // The remaining checks depend on the data arguments.
3646 if (HasVAListArg)
3647 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003648
Ted Kremenek666a1972010-07-26 19:45:42 +00003649 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003650 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003651
Jordan Rose48716662012-07-19 18:10:08 +00003652 const Expr *Arg = getDataArg(argIndex);
3653 if (!Arg)
3654 return true;
3655
3656 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003657}
3658
Jordan Roseec087352012-09-05 22:56:26 +00003659static bool requiresParensToAddCast(const Expr *E) {
3660 // FIXME: We should have a general way to reason about operator
3661 // precedence and whether parens are actually needed here.
3662 // Take care of a few common cases where they aren't.
3663 const Expr *Inside = E->IgnoreImpCasts();
3664 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3665 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3666
3667 switch (Inside->getStmtClass()) {
3668 case Stmt::ArraySubscriptExprClass:
3669 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003670 case Stmt::CharacterLiteralClass:
3671 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003672 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003673 case Stmt::FloatingLiteralClass:
3674 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003675 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003676 case Stmt::ObjCArrayLiteralClass:
3677 case Stmt::ObjCBoolLiteralExprClass:
3678 case Stmt::ObjCBoxedExprClass:
3679 case Stmt::ObjCDictionaryLiteralClass:
3680 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003681 case Stmt::ObjCIvarRefExprClass:
3682 case Stmt::ObjCMessageExprClass:
3683 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003684 case Stmt::ObjCStringLiteralClass:
3685 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003686 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003687 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003688 case Stmt::UnaryOperatorClass:
3689 return false;
3690 default:
3691 return true;
3692 }
3693}
3694
Stephen Hines176edba2014-12-01 14:53:08 -08003695static std::pair<QualType, StringRef>
3696shouldNotPrintDirectly(const ASTContext &Context,
3697 QualType IntendedTy,
3698 const Expr *E) {
3699 // Use a 'while' to peel off layers of typedefs.
3700 QualType TyTy = IntendedTy;
3701 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3702 StringRef Name = UserTy->getDecl()->getName();
3703 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3704 .Case("NSInteger", Context.LongTy)
3705 .Case("NSUInteger", Context.UnsignedLongTy)
3706 .Case("SInt32", Context.IntTy)
3707 .Case("UInt32", Context.UnsignedIntTy)
3708 .Default(QualType());
3709
3710 if (!CastTy.isNull())
3711 return std::make_pair(CastTy, Name);
3712
3713 TyTy = UserTy->desugar();
3714 }
3715
3716 // Strip parens if necessary.
3717 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3718 return shouldNotPrintDirectly(Context,
3719 PE->getSubExpr()->getType(),
3720 PE->getSubExpr());
3721
3722 // If this is a conditional expression, then its result type is constructed
3723 // via usual arithmetic conversions and thus there might be no necessary
3724 // typedef sugar there. Recurse to operands to check for NSInteger &
3725 // Co. usage condition.
3726 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3727 QualType TrueTy, FalseTy;
3728 StringRef TrueName, FalseName;
3729
3730 std::tie(TrueTy, TrueName) =
3731 shouldNotPrintDirectly(Context,
3732 CO->getTrueExpr()->getType(),
3733 CO->getTrueExpr());
3734 std::tie(FalseTy, FalseName) =
3735 shouldNotPrintDirectly(Context,
3736 CO->getFalseExpr()->getType(),
3737 CO->getFalseExpr());
3738
3739 if (TrueTy == FalseTy)
3740 return std::make_pair(TrueTy, TrueName);
3741 else if (TrueTy.isNull())
3742 return std::make_pair(FalseTy, FalseName);
3743 else if (FalseTy.isNull())
3744 return std::make_pair(TrueTy, TrueName);
3745 }
3746
3747 return std::make_pair(QualType(), StringRef());
3748}
3749
Richard Smith831421f2012-06-25 20:30:08 +00003750bool
3751CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3752 const char *StartSpecifier,
3753 unsigned SpecifierLen,
3754 const Expr *E) {
3755 using namespace analyze_format_string;
3756 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003757 // Now type check the data expression that matches the
3758 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003759 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3760 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003761 if (!AT.isValid())
3762 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003763
Jordan Rose448ac3e2012-12-05 18:44:40 +00003764 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003765 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3766 ExprTy = TET->getUnderlyingExpr()->getType();
3767 }
3768
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003769 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3770
3771 if (match == analyze_printf::ArgType::Match) {
Jordan Rose614a8652012-09-05 22:56:19 +00003772 return true;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003773 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003774
Jordan Rose614a8652012-09-05 22:56:19 +00003775 // Look through argument promotions for our error message's reported type.
3776 // This includes the integral and floating promotions, but excludes array
3777 // and function pointer decay; seeing that an argument intended to be a
3778 // string has type 'char [6]' is probably more confusing than 'char *'.
3779 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3780 if (ICE->getCastKind() == CK_IntegralCast ||
3781 ICE->getCastKind() == CK_FloatingCast) {
3782 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003783 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003784
3785 // Check if we didn't match because of an implicit cast from a 'char'
3786 // or 'short' to an 'int'. This is done because printf is a varargs
3787 // function.
3788 if (ICE->getType() == S.Context.IntTy ||
3789 ICE->getType() == S.Context.UnsignedIntTy) {
3790 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003791 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003792 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003793 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003794 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003795 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3796 // Special case for 'a', which has type 'int' in C.
3797 // Note, however, that we do /not/ want to treat multibyte constants like
3798 // 'MooV' as characters! This form is deprecated but still exists.
3799 if (ExprTy == S.Context.IntTy)
3800 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3801 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003802 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003803
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003804 // Look through enums to their underlying type.
3805 bool IsEnum = false;
3806 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3807 ExprTy = EnumTy->getDecl()->getIntegerType();
3808 IsEnum = true;
3809 }
3810
Jordan Rose2cd34402012-12-05 18:44:49 +00003811 // %C in an Objective-C context prints a unichar, not a wchar_t.
3812 // If the argument is an integer of some kind, believe the %C and suggest
3813 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003814 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003815 if (ObjCContext &&
3816 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3817 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3818 !ExprTy->isCharType()) {
3819 // 'unichar' is defined as a typedef of unsigned short, but we should
3820 // prefer using the typedef if it is visible.
3821 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003822
3823 // While we are here, check if the value is an IntegerLiteral that happens
3824 // to be within the valid range.
3825 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3826 const llvm::APInt &V = IL->getValue();
3827 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3828 return true;
3829 }
3830
Jordan Rose2cd34402012-12-05 18:44:49 +00003831 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3832 Sema::LookupOrdinaryName);
3833 if (S.LookupName(Result, S.getCurScope())) {
3834 NamedDecl *ND = Result.getFoundDecl();
3835 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3836 if (TD->getUnderlyingType() == IntendedTy)
3837 IntendedTy = S.Context.getTypedefType(TD);
3838 }
3839 }
3840 }
3841
3842 // Special-case some of Darwin's platform-independence types by suggesting
3843 // casts to primitive types that are known to be large enough.
Stephen Hines176edba2014-12-01 14:53:08 -08003844 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseec087352012-09-05 22:56:26 +00003845 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003846 QualType CastTy;
3847 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3848 if (!CastTy.isNull()) {
3849 IntendedTy = CastTy;
3850 ShouldNotPrintDirectly = true;
Jordan Roseec087352012-09-05 22:56:26 +00003851 }
3852 }
3853
Jordan Rose614a8652012-09-05 22:56:19 +00003854 // We may be able to offer a FixItHint if it is a supported type.
3855 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003856 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003857 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003858
Jordan Rose614a8652012-09-05 22:56:19 +00003859 if (success) {
3860 // Get the fix string from the fixed format specifier
3861 SmallString<16> buf;
3862 llvm::raw_svector_ostream os(buf);
3863 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003864
Jordan Roseec087352012-09-05 22:56:26 +00003865 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3866
Stephen Hines176edba2014-12-01 14:53:08 -08003867 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003868 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3869 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3870 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3871 }
Jordan Rose2cd34402012-12-05 18:44:49 +00003872 // In this case, the specifier is wrong and should be changed to match
3873 // the argument.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003874 EmitFormatDiagnostic(S.PDiag(diag)
3875 << AT.getRepresentativeTypeName(S.Context)
3876 << IntendedTy << IsEnum << E->getSourceRange(),
3877 E->getLocStart(),
3878 /*IsStringLocation*/ false, SpecRange,
3879 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose2cd34402012-12-05 18:44:49 +00003880
3881 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003882 // The canonical type for formatting this value is different from the
3883 // actual type of the expression. (This occurs, for example, with Darwin's
3884 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3885 // should be printed as 'long' for 64-bit compatibility.)
3886 // Rather than emitting a normal format/argument mismatch, we want to
3887 // add a cast to the recommended type (and correct the format string
3888 // if necessary).
3889 SmallString<16> CastBuf;
3890 llvm::raw_svector_ostream CastFix(CastBuf);
3891 CastFix << "(";
3892 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3893 CastFix << ")";
3894
3895 SmallVector<FixItHint,4> Hints;
3896 if (!AT.matchesType(S.Context, IntendedTy))
3897 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3898
3899 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3900 // If there's already a cast present, just replace it.
3901 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3902 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3903
3904 } else if (!requiresParensToAddCast(E)) {
3905 // If the expression has high enough precedence,
3906 // just write the C-style cast.
3907 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3908 CastFix.str()));
3909 } else {
3910 // Otherwise, add parens around the expression as well as the cast.
3911 CastFix << "(";
3912 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3913 CastFix.str()));
3914
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003915 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseec087352012-09-05 22:56:26 +00003916 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3917 }
3918
Jordan Rose2cd34402012-12-05 18:44:49 +00003919 if (ShouldNotPrintDirectly) {
3920 // The expression has a type that should not be printed directly.
3921 // We extract the name from the typedef because we don't want to show
3922 // the underlying type in the diagnostic.
Stephen Hines176edba2014-12-01 14:53:08 -08003923 StringRef Name;
3924 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3925 Name = TypedefTy->getDecl()->getName();
3926 else
3927 Name = CastTyName;
Jordan Rose2cd34402012-12-05 18:44:49 +00003928 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003929 << Name << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003930 << E->getSourceRange(),
3931 E->getLocStart(), /*IsStringLocation=*/false,
3932 SpecRange, Hints);
3933 } else {
3934 // In this case, the expression could be printed using a different
3935 // specifier, but we've decided that the specifier is probably correct
3936 // and we should cast instead. Just use the normal warning message.
3937 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003938 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3939 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003940 << E->getSourceRange(),
3941 E->getLocStart(), /*IsStringLocation*/false,
3942 SpecRange, Hints);
3943 }
Jordan Roseec087352012-09-05 22:56:26 +00003944 }
Jordan Rose614a8652012-09-05 22:56:19 +00003945 } else {
3946 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3947 SpecifierLen);
3948 // Since the warning for passing non-POD types to variadic functions
3949 // was deferred until now, we emit a warning for non-POD
3950 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003951 switch (S.isValidVarArgType(ExprTy)) {
3952 case Sema::VAK_Valid:
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003953 case Sema::VAK_ValidInCXX11: {
3954 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3955 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3956 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3957 }
Richard Smith0e218972013-08-05 18:49:43 +00003958
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003959 EmitFormatDiagnostic(
3960 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3961 << IsEnum << CSR << E->getSourceRange(),
3962 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3963 break;
3964 }
Richard Smith0e218972013-08-05 18:49:43 +00003965 case Sema::VAK_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08003966 case Sema::VAK_MSVCUndefined:
Richard Smith0e218972013-08-05 18:49:43 +00003967 EmitFormatDiagnostic(
3968 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003969 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003970 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003971 << CallType
3972 << AT.getRepresentativeTypeName(S.Context)
3973 << CSR
3974 << E->getSourceRange(),
3975 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003976 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003977 break;
3978
3979 case Sema::VAK_Invalid:
3980 if (ExprTy->isObjCObjectType())
3981 EmitFormatDiagnostic(
3982 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3983 << S.getLangOpts().CPlusPlus11
3984 << ExprTy
3985 << CallType
3986 << AT.getRepresentativeTypeName(S.Context)
3987 << CSR
3988 << E->getSourceRange(),
3989 E->getLocStart(), /*IsStringLocation*/false, CSR);
3990 else
3991 // FIXME: If this is an initializer list, suggest removing the braces
3992 // or inserting a cast to the target type.
3993 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3994 << isa<InitListExpr>(E) << ExprTy << CallType
3995 << AT.getRepresentativeTypeName(S.Context)
3996 << E->getSourceRange();
3997 break;
3998 }
3999
4000 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4001 "format string specifier index out of range");
4002 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00004003 }
4004
Ted Kremeneke0e53132010-01-28 23:39:18 +00004005 return true;
4006}
4007
Ted Kremenek826a3452010-07-16 02:11:22 +00004008//===--- CHECK: Scanf format string checking ------------------------------===//
4009
4010namespace {
4011class CheckScanfHandler : public CheckFormatHandler {
4012public:
4013 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4014 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00004015 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004016 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00004017 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00004018 Sema::VariadicCallType CallType,
4019 llvm::SmallBitVector &CheckedVarArgs)
4020 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4021 numDataArgs, beg, hasVAListArg,
4022 Args, formatIdx, inFunctionCall, CallType,
4023 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00004024 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00004025
4026 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4027 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07004028 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00004029
4030 bool HandleInvalidScanfConversionSpecifier(
4031 const analyze_scanf::ScanfSpecifier &FS,
4032 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07004033 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00004034
Stephen Hines651f13c2014-04-23 16:59:28 -07004035 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00004036};
Ted Kremenek07d161f2010-01-29 01:50:07 +00004037}
Ted Kremeneke0e53132010-01-28 23:39:18 +00004038
Ted Kremenekb7c21012010-07-16 18:28:03 +00004039void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4040 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00004041 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4042 getLocationOfByte(end), /*IsStringLocation*/true,
4043 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00004044}
4045
Ted Kremenekc09b6a52010-07-19 21:25:57 +00004046bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4047 const analyze_scanf::ScanfSpecifier &FS,
4048 const char *startSpecifier,
4049 unsigned specifierLen) {
4050
Ted Kremenek6ecb9502010-07-20 20:04:27 +00004051 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00004052 FS.getConversionSpecifier();
4053
4054 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4055 getLocationOfByte(CS.getStart()),
4056 startSpecifier, specifierLen,
4057 CS.getStart(), CS.getLength());
4058}
4059
Ted Kremenek826a3452010-07-16 02:11:22 +00004060bool CheckScanfHandler::HandleScanfSpecifier(
4061 const analyze_scanf::ScanfSpecifier &FS,
4062 const char *startSpecifier,
4063 unsigned specifierLen) {
4064
4065 using namespace analyze_scanf;
4066 using namespace analyze_format_string;
4067
Ted Kremenek6ecb9502010-07-20 20:04:27 +00004068 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00004069
Ted Kremenekbaa40062010-07-19 22:01:06 +00004070 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4071 // be used to decide if we are using positional arguments consistently.
4072 if (FS.consumesDataArgument()) {
4073 if (atFirstArg) {
4074 atFirstArg = false;
4075 usesPositionalArgs = FS.usesPositionalArg();
4076 }
4077 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00004078 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4079 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00004080 return false;
4081 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004082 }
4083
4084 // Check if the field with is non-zero.
4085 const OptionalAmount &Amt = FS.getFieldWidth();
4086 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4087 if (Amt.getConstantAmount() == 0) {
4088 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4089 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00004090 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4091 getLocationOfByte(Amt.getStart()),
4092 /*IsStringLocation*/true, R,
4093 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00004094 }
4095 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004096
Ted Kremenek826a3452010-07-16 02:11:22 +00004097 if (!FS.consumesDataArgument()) {
4098 // FIXME: Technically specifying a precision or field width here
4099 // makes no sense. Worth issuing a warning at some point.
4100 return true;
4101 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004102
Ted Kremenek826a3452010-07-16 02:11:22 +00004103 // Consume the argument.
4104 unsigned argIndex = FS.getArgIndex();
4105 if (argIndex < NumDataArgs) {
4106 // The check to see if the argIndex is valid will come later.
4107 // We set the bit here because we may exit early from this
4108 // function if we encounter some other error.
4109 CoveredArgs.set(argIndex);
4110 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004111
Ted Kremenek1e51c202010-07-20 20:04:47 +00004112 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004113 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00004114 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4115 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004116 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00004117 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004118 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00004119 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4120 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00004121
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004122 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4123 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4124
Ted Kremenek826a3452010-07-16 02:11:22 +00004125 // The remaining checks depend on the data arguments.
4126 if (HasVAListArg)
4127 return true;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004128
Ted Kremenek666a1972010-07-26 19:45:42 +00004129 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00004130 return false;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004131
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004132 // Check that the argument type matches the format specifier.
4133 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00004134 if (!Ex)
4135 return true;
4136
Hans Wennborg58e1e542012-08-07 08:59:46 +00004137 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004138
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004139 if (!AT.isValid()) {
4140 return true;
4141 }
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004142
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004143 analyze_format_string::ArgType::MatchKind match =
4144 AT.matchesType(S.Context, Ex->getType());
4145 if (match == analyze_format_string::ArgType::Match) {
4146 return true;
4147 }
4148
4149 ScanfSpecifier fixedFS = FS;
4150 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4151 S.getLangOpts(), S.Context);
4152
4153 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4154 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4155 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4156 }
4157
4158 if (success) {
4159 // Get the fix string from the fixed format specifier.
4160 SmallString<128> buf;
4161 llvm::raw_svector_ostream os(buf);
4162 fixedFS.toString(os);
4163
4164 EmitFormatDiagnostic(
4165 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4166 << Ex->getType() << false << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00004167 Ex->getLocStart(),
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004168 /*IsStringLocation*/ false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004169 getSpecifierRange(startSpecifier, specifierLen),
4170 FixItHint::CreateReplacement(
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004171 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4172 } else {
4173 EmitFormatDiagnostic(S.PDiag(diag)
4174 << AT.getRepresentativeTypeName(S.Context)
4175 << Ex->getType() << false << Ex->getSourceRange(),
4176 Ex->getLocStart(),
4177 /*IsStringLocation*/ false,
4178 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004179 }
4180
Ted Kremenek826a3452010-07-16 02:11:22 +00004181 return true;
4182}
4183
4184void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00004185 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004186 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004187 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004188 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00004189 bool inFunctionCall, VariadicCallType CallType,
4190 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004191
Ted Kremeneke0e53132010-01-28 23:39:18 +00004192 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00004193 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00004194 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004195 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004196 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4197 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004198 return;
4199 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004200
Ted Kremeneke0e53132010-01-28 23:39:18 +00004201 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00004202 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00004203 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07004204 // Account for cases where the string literal is truncated in a declaration.
4205 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4206 assert(T && "String literal not of constant array type!");
4207 size_t TypeSize = T->getSize().getZExtValue();
4208 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004209 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07004210
4211 // Emit a warning if the string literal is truncated and does not contain an
4212 // embedded null character.
4213 if (TypeSize <= StrRef.size() &&
4214 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4215 CheckFormatHandler::EmitFormatDiagnostic(
4216 *this, inFunctionCall, Args[format_idx],
4217 PDiag(diag::warn_printf_format_string_not_null_terminated),
4218 FExpr->getLocStart(),
4219 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4220 return;
4221 }
4222
Ted Kremeneke0e53132010-01-28 23:39:18 +00004223 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00004224 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00004225 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004226 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004227 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4228 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004229 return;
4230 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004231
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004232 if (Type == FST_Printf || Type == FST_NSString ||
4233 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004234 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004235 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004236 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004237 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004238
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004239 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004240 getLangOpts(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004241 Context.getTargetInfo(),
4242 Type == FST_FreeBSDKPrintf))
Ted Kremenek826a3452010-07-16 02:11:22 +00004243 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004244 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00004245 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004246 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004247 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004248
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004249 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004250 getLangOpts(),
4251 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00004252 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004253 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00004254}
4255
Stephen Hines176edba2014-12-01 14:53:08 -08004256bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4257 // Str - The format string. NOTE: this is NOT null-terminated!
4258 StringRef StrRef = FExpr->getString();
4259 const char *Str = StrRef.data();
4260 // Account for cases where the string literal is truncated in a declaration.
4261 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4262 assert(T && "String literal not of constant array type!");
4263 size_t TypeSize = T->getSize().getZExtValue();
4264 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4265 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4266 getLangOpts(),
4267 Context.getTargetInfo());
4268}
4269
Stephen Hines651f13c2014-04-23 16:59:28 -07004270//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4271
4272// Returns the related absolute value function that is larger, of 0 if one
4273// does not exist.
4274static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4275 switch (AbsFunction) {
4276 default:
4277 return 0;
4278
4279 case Builtin::BI__builtin_abs:
4280 return Builtin::BI__builtin_labs;
4281 case Builtin::BI__builtin_labs:
4282 return Builtin::BI__builtin_llabs;
4283 case Builtin::BI__builtin_llabs:
4284 return 0;
4285
4286 case Builtin::BI__builtin_fabsf:
4287 return Builtin::BI__builtin_fabs;
4288 case Builtin::BI__builtin_fabs:
4289 return Builtin::BI__builtin_fabsl;
4290 case Builtin::BI__builtin_fabsl:
4291 return 0;
4292
4293 case Builtin::BI__builtin_cabsf:
4294 return Builtin::BI__builtin_cabs;
4295 case Builtin::BI__builtin_cabs:
4296 return Builtin::BI__builtin_cabsl;
4297 case Builtin::BI__builtin_cabsl:
4298 return 0;
4299
4300 case Builtin::BIabs:
4301 return Builtin::BIlabs;
4302 case Builtin::BIlabs:
4303 return Builtin::BIllabs;
4304 case Builtin::BIllabs:
4305 return 0;
4306
4307 case Builtin::BIfabsf:
4308 return Builtin::BIfabs;
4309 case Builtin::BIfabs:
4310 return Builtin::BIfabsl;
4311 case Builtin::BIfabsl:
4312 return 0;
4313
4314 case Builtin::BIcabsf:
4315 return Builtin::BIcabs;
4316 case Builtin::BIcabs:
4317 return Builtin::BIcabsl;
4318 case Builtin::BIcabsl:
4319 return 0;
4320 }
4321}
4322
4323// Returns the argument type of the absolute value function.
4324static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4325 unsigned AbsType) {
4326 if (AbsType == 0)
4327 return QualType();
4328
4329 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4330 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4331 if (Error != ASTContext::GE_None)
4332 return QualType();
4333
4334 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4335 if (!FT)
4336 return QualType();
4337
4338 if (FT->getNumParams() != 1)
4339 return QualType();
4340
4341 return FT->getParamType(0);
4342}
4343
4344// Returns the best absolute value function, or zero, based on type and
4345// current absolute value function.
4346static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4347 unsigned AbsFunctionKind) {
4348 unsigned BestKind = 0;
4349 uint64_t ArgSize = Context.getTypeSize(ArgType);
4350 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4351 Kind = getLargerAbsoluteValueFunction(Kind)) {
4352 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4353 if (Context.getTypeSize(ParamType) >= ArgSize) {
4354 if (BestKind == 0)
4355 BestKind = Kind;
4356 else if (Context.hasSameType(ParamType, ArgType)) {
4357 BestKind = Kind;
4358 break;
4359 }
4360 }
4361 }
4362 return BestKind;
4363}
4364
4365enum AbsoluteValueKind {
4366 AVK_Integer,
4367 AVK_Floating,
4368 AVK_Complex
4369};
4370
4371static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4372 if (T->isIntegralOrEnumerationType())
4373 return AVK_Integer;
4374 if (T->isRealFloatingType())
4375 return AVK_Floating;
4376 if (T->isAnyComplexType())
4377 return AVK_Complex;
4378
4379 llvm_unreachable("Type not integer, floating, or complex");
4380}
4381
4382// Changes the absolute value function to a different type. Preserves whether
4383// the function is a builtin.
4384static unsigned changeAbsFunction(unsigned AbsKind,
4385 AbsoluteValueKind ValueKind) {
4386 switch (ValueKind) {
4387 case AVK_Integer:
4388 switch (AbsKind) {
4389 default:
4390 return 0;
4391 case Builtin::BI__builtin_fabsf:
4392 case Builtin::BI__builtin_fabs:
4393 case Builtin::BI__builtin_fabsl:
4394 case Builtin::BI__builtin_cabsf:
4395 case Builtin::BI__builtin_cabs:
4396 case Builtin::BI__builtin_cabsl:
4397 return Builtin::BI__builtin_abs;
4398 case Builtin::BIfabsf:
4399 case Builtin::BIfabs:
4400 case Builtin::BIfabsl:
4401 case Builtin::BIcabsf:
4402 case Builtin::BIcabs:
4403 case Builtin::BIcabsl:
4404 return Builtin::BIabs;
4405 }
4406 case AVK_Floating:
4407 switch (AbsKind) {
4408 default:
4409 return 0;
4410 case Builtin::BI__builtin_abs:
4411 case Builtin::BI__builtin_labs:
4412 case Builtin::BI__builtin_llabs:
4413 case Builtin::BI__builtin_cabsf:
4414 case Builtin::BI__builtin_cabs:
4415 case Builtin::BI__builtin_cabsl:
4416 return Builtin::BI__builtin_fabsf;
4417 case Builtin::BIabs:
4418 case Builtin::BIlabs:
4419 case Builtin::BIllabs:
4420 case Builtin::BIcabsf:
4421 case Builtin::BIcabs:
4422 case Builtin::BIcabsl:
4423 return Builtin::BIfabsf;
4424 }
4425 case AVK_Complex:
4426 switch (AbsKind) {
4427 default:
4428 return 0;
4429 case Builtin::BI__builtin_abs:
4430 case Builtin::BI__builtin_labs:
4431 case Builtin::BI__builtin_llabs:
4432 case Builtin::BI__builtin_fabsf:
4433 case Builtin::BI__builtin_fabs:
4434 case Builtin::BI__builtin_fabsl:
4435 return Builtin::BI__builtin_cabsf;
4436 case Builtin::BIabs:
4437 case Builtin::BIlabs:
4438 case Builtin::BIllabs:
4439 case Builtin::BIfabsf:
4440 case Builtin::BIfabs:
4441 case Builtin::BIfabsl:
4442 return Builtin::BIcabsf;
4443 }
4444 }
4445 llvm_unreachable("Unable to convert function");
4446}
4447
4448static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4449 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4450 if (!FnInfo)
4451 return 0;
4452
4453 switch (FDecl->getBuiltinID()) {
4454 default:
4455 return 0;
4456 case Builtin::BI__builtin_abs:
4457 case Builtin::BI__builtin_fabs:
4458 case Builtin::BI__builtin_fabsf:
4459 case Builtin::BI__builtin_fabsl:
4460 case Builtin::BI__builtin_labs:
4461 case Builtin::BI__builtin_llabs:
4462 case Builtin::BI__builtin_cabs:
4463 case Builtin::BI__builtin_cabsf:
4464 case Builtin::BI__builtin_cabsl:
4465 case Builtin::BIabs:
4466 case Builtin::BIlabs:
4467 case Builtin::BIllabs:
4468 case Builtin::BIfabs:
4469 case Builtin::BIfabsf:
4470 case Builtin::BIfabsl:
4471 case Builtin::BIcabs:
4472 case Builtin::BIcabsf:
4473 case Builtin::BIcabsl:
4474 return FDecl->getBuiltinID();
4475 }
4476 llvm_unreachable("Unknown Builtin type");
4477}
4478
4479// If the replacement is valid, emit a note with replacement function.
4480// Additionally, suggest including the proper header if not already included.
4481static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004482 unsigned AbsKind, QualType ArgType) {
4483 bool EmitHeaderHint = true;
4484 const char *HeaderName = nullptr;
4485 const char *FunctionName = nullptr;
4486 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4487 FunctionName = "std::abs";
4488 if (ArgType->isIntegralOrEnumerationType()) {
4489 HeaderName = "cstdlib";
4490 } else if (ArgType->isRealFloatingType()) {
4491 HeaderName = "cmath";
4492 } else {
4493 llvm_unreachable("Invalid Type");
Stephen Hines651f13c2014-04-23 16:59:28 -07004494 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004495
4496 // Lookup all std::abs
4497 if (NamespaceDecl *Std = S.getStdNamespace()) {
4498 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4499 R.suppressDiagnostics();
4500 S.LookupQualifiedName(R, Std);
4501
4502 for (const auto *I : R) {
4503 const FunctionDecl *FDecl = nullptr;
4504 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4505 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4506 } else {
4507 FDecl = dyn_cast<FunctionDecl>(I);
4508 }
4509 if (!FDecl)
4510 continue;
4511
4512 // Found std::abs(), check that they are the right ones.
4513 if (FDecl->getNumParams() != 1)
4514 continue;
4515
4516 // Check that the parameter type can handle the argument.
4517 QualType ParamType = FDecl->getParamDecl(0)->getType();
4518 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4519 S.Context.getTypeSize(ArgType) <=
4520 S.Context.getTypeSize(ParamType)) {
4521 // Found a function, don't need the header hint.
4522 EmitHeaderHint = false;
4523 break;
4524 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004525 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004526 }
4527 } else {
4528 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4529 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4530
4531 if (HeaderName) {
4532 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4533 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4534 R.suppressDiagnostics();
4535 S.LookupName(R, S.getCurScope());
4536
4537 if (R.isSingleResult()) {
4538 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4539 if (FD && FD->getBuiltinID() == AbsKind) {
4540 EmitHeaderHint = false;
4541 } else {
4542 return;
4543 }
4544 } else if (!R.empty()) {
4545 return;
4546 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004547 }
4548 }
4549
4550 S.Diag(Loc, diag::note_replace_abs_function)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004551 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Stephen Hines651f13c2014-04-23 16:59:28 -07004552
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004553 if (!HeaderName)
4554 return;
4555
4556 if (!EmitHeaderHint)
4557 return;
4558
Stephen Hines176edba2014-12-01 14:53:08 -08004559 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4560 << FunctionName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004561}
4562
4563static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4564 if (!FDecl)
4565 return false;
4566
4567 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4568 return false;
4569
4570 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4571
4572 while (ND && ND->isInlineNamespace()) {
4573 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004574 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004575
4576 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4577 return false;
4578
4579 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4580 return false;
4581
4582 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004583}
4584
4585// Warn when using the wrong abs() function.
4586void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4587 const FunctionDecl *FDecl,
4588 IdentifierInfo *FnInfo) {
4589 if (Call->getNumArgs() != 1)
4590 return;
4591
4592 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004593 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4594 if (AbsKind == 0 && !IsStdAbs)
Stephen Hines651f13c2014-04-23 16:59:28 -07004595 return;
4596
4597 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4598 QualType ParamType = Call->getArg(0)->getType();
4599
Stephen Hines176edba2014-12-01 14:53:08 -08004600 // Unsigned types cannot be negative. Suggest removing the absolute value
4601 // function call.
Stephen Hines651f13c2014-04-23 16:59:28 -07004602 if (ArgType->isUnsignedIntegerType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004603 const char *FunctionName =
4604 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07004605 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4606 Diag(Call->getExprLoc(), diag::note_remove_abs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004607 << FunctionName
Stephen Hines651f13c2014-04-23 16:59:28 -07004608 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4609 return;
4610 }
4611
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004612 // std::abs has overloads which prevent most of the absolute value problems
4613 // from occurring.
4614 if (IsStdAbs)
4615 return;
4616
Stephen Hines651f13c2014-04-23 16:59:28 -07004617 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4618 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4619
4620 // The argument and parameter are the same kind. Check if they are the right
4621 // size.
4622 if (ArgValueKind == ParamValueKind) {
4623 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4624 return;
4625
4626 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4627 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4628 << FDecl << ArgType << ParamType;
4629
4630 if (NewAbsKind == 0)
4631 return;
4632
4633 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004634 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004635 return;
4636 }
4637
4638 // ArgValueKind != ParamValueKind
4639 // The wrong type of absolute value function was used. Attempt to find the
4640 // proper one.
4641 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4642 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4643 if (NewAbsKind == 0)
4644 return;
4645
4646 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4647 << FDecl << ParamValueKind << ArgValueKind;
4648
4649 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004650 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004651 return;
4652}
4653
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004654//===--- CHECK: Standard memory functions ---------------------------------===//
4655
Stephen Hines651f13c2014-04-23 16:59:28 -07004656/// \brief Takes the expression passed to the size_t parameter of functions
4657/// such as memcmp, strncat, etc and warns if it's a comparison.
4658///
4659/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4660static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4661 IdentifierInfo *FnName,
4662 SourceLocation FnLoc,
4663 SourceLocation RParenLoc) {
4664 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4665 if (!Size)
4666 return false;
4667
4668 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4669 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4670 return false;
4671
Stephen Hines651f13c2014-04-23 16:59:28 -07004672 SourceRange SizeRange = Size->getSourceRange();
4673 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4674 << SizeRange << FnName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004675 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4676 << FnName << FixItHint::CreateInsertion(
4677 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Stephen Hines651f13c2014-04-23 16:59:28 -07004678 << FixItHint::CreateRemoval(RParenLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004679 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Stephen Hines651f13c2014-04-23 16:59:28 -07004680 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004681 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4682 ")");
Stephen Hines651f13c2014-04-23 16:59:28 -07004683
4684 return true;
4685}
4686
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004687/// \brief Determine whether the given type is or contains a dynamic class type
4688/// (e.g., whether it has a vtable).
4689static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4690 bool &IsContained) {
4691 // Look through array types while ignoring qualifiers.
4692 const Type *Ty = T->getBaseElementTypeUnsafe();
4693 IsContained = false;
4694
4695 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4696 RD = RD ? RD->getDefinition() : nullptr;
4697 if (!RD)
4698 return nullptr;
4699
4700 if (RD->isDynamicClass())
4701 return RD;
4702
4703 // Check all the fields. If any bases were dynamic, the class is dynamic.
4704 // It's impossible for a class to transitively contain itself by value, so
4705 // infinite recursion is impossible.
4706 for (auto *FD : RD->fields()) {
4707 bool SubContained;
4708 if (const CXXRecordDecl *ContainedRD =
4709 getContainedDynamicClass(FD->getType(), SubContained)) {
4710 IsContained = true;
4711 return ContainedRD;
4712 }
4713 }
4714
4715 return nullptr;
Douglas Gregor2a053a32011-05-03 20:05:22 +00004716}
4717
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004718/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00004719/// otherwise returns NULL.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004720static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Webere4a1c642011-06-14 16:14:58 +00004721 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00004722 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4723 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4724 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004725
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004726 return nullptr;
Chandler Carruth000d4282011-06-16 09:09:40 +00004727}
4728
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004729/// \brief If E is a sizeof expression, returns its argument type.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004730static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004731 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4732 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4733 if (SizeOf->getKind() == clang::UETT_SizeOf)
4734 return SizeOf->getTypeOfArgument();
4735
4736 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00004737}
4738
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004739/// \brief Check for dangerous or invalid arguments to memset().
4740///
Chandler Carruth929f0132011-06-03 06:23:57 +00004741/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004742/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4743/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004744///
4745/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004746void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004747 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004748 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004749 assert(BId != 0);
4750
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004751 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004752 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004753 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004754 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004755 return;
4756
Anna Zaks0a151a12012-01-17 00:37:07 +00004757 unsigned LastArg = (BId == Builtin::BImemset ||
4758 BId == Builtin::BIstrndup ? 1 : 2);
4759 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004760 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004761
Stephen Hines651f13c2014-04-23 16:59:28 -07004762 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4763 Call->getLocStart(), Call->getRParenLoc()))
4764 return;
4765
Chandler Carruth000d4282011-06-16 09:09:40 +00004766 // We have special checking when the length is a sizeof expression.
4767 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4768 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4769 llvm::FoldingSetNodeID SizeOfArgID;
4770
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004771 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4772 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004773 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004774
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004775 QualType DestTy = Dest->getType();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004776 QualType PointeeTy;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004777 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004778 PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004779
Chandler Carruth000d4282011-06-16 09:09:40 +00004780 // Never warn about void type pointers. This can be used to suppress
4781 // false positives.
4782 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004783 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004784
Chandler Carruth000d4282011-06-16 09:09:40 +00004785 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4786 // actually comparing the expressions for equality. Because computing the
4787 // expression IDs can be expensive, we only do this if the diagnostic is
4788 // enabled.
4789 if (SizeOfArg &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004790 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4791 SizeOfArg->getExprLoc())) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004792 // We only compute IDs for expressions if the warning is enabled, and
4793 // cache the sizeof arg's ID.
4794 if (SizeOfArgID == llvm::FoldingSetNodeID())
4795 SizeOfArg->Profile(SizeOfArgID, Context, true);
4796 llvm::FoldingSetNodeID DestID;
4797 Dest->Profile(DestID, Context, true);
4798 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004799 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4800 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004801 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004802 StringRef ReadableName = FnName->getName();
4803
Chandler Carruth000d4282011-06-16 09:09:40 +00004804 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004805 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004806 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004807 if (!PointeeTy->isIncompleteType() &&
4808 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004809 ActionIdx = 2; // If the pointee's size is sizeof(char),
4810 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004811
4812 // If the function is defined as a builtin macro, do not show macro
4813 // expansion.
4814 SourceLocation SL = SizeOfArg->getExprLoc();
4815 SourceRange DSR = Dest->getSourceRange();
4816 SourceRange SSR = SizeOfArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004817 SourceManager &SM = getSourceManager();
Anna Zaks6fcb3722012-05-30 00:34:21 +00004818
4819 if (SM.isMacroArgExpansion(SL)) {
4820 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4821 SL = SM.getSpellingLoc(SL);
4822 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4823 SM.getSpellingLoc(DSR.getEnd()));
4824 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4825 SM.getSpellingLoc(SSR.getEnd()));
4826 }
4827
Anna Zaks90c78322012-05-30 23:14:52 +00004828 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004829 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004830 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004831 << PointeeTy
4832 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004833 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004834 << SSR);
4835 DiagRuntimeBehavior(SL, SizeOfArg,
4836 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4837 << ActionIdx
4838 << SSR);
4839
Chandler Carruth000d4282011-06-16 09:09:40 +00004840 break;
4841 }
4842 }
4843
4844 // Also check for cases where the sizeof argument is the exact same
4845 // type as the memory argument, and where it points to a user-defined
4846 // record type.
4847 if (SizeOfArgTy != QualType()) {
4848 if (PointeeTy->isRecordType() &&
4849 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4850 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4851 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4852 << FnName << SizeOfArgTy << ArgIdx
4853 << PointeeTy << Dest->getSourceRange()
4854 << LenExpr->getSourceRange());
4855 break;
4856 }
Nico Webere4a1c642011-06-14 16:14:58 +00004857 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004858 } else if (DestTy->isArrayType()) {
4859 PointeeTy = DestTy;
4860 }
Nico Webere4a1c642011-06-14 16:14:58 +00004861
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004862 if (PointeeTy == QualType())
4863 continue;
Anna Zaks0a151a12012-01-17 00:37:07 +00004864
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004865 // Always complain about dynamic classes.
4866 bool IsContained;
4867 if (const CXXRecordDecl *ContainedRD =
4868 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCallf85e1932011-06-15 23:02:42 +00004869
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004870 unsigned OperationType = 0;
4871 // "overwritten" if we're warning about the destination for any call
4872 // but memcmp; otherwise a verb appropriate to the call.
4873 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4874 if (BId == Builtin::BImemcpy)
4875 OperationType = 1;
4876 else if(BId == Builtin::BImemmove)
4877 OperationType = 2;
4878 else if (BId == Builtin::BImemcmp)
4879 OperationType = 3;
4880 }
4881
John McCallf85e1932011-06-15 23:02:42 +00004882 DiagRuntimeBehavior(
4883 Dest->getExprLoc(), Dest,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004884 PDiag(diag::warn_dyn_class_memaccess)
4885 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4886 << FnName << IsContained << ContainedRD << OperationType
4887 << Call->getCallee()->getSourceRange());
4888 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4889 BId != Builtin::BImemset)
4890 DiagRuntimeBehavior(
4891 Dest->getExprLoc(), Dest,
4892 PDiag(diag::warn_arc_object_memaccess)
4893 << ArgIdx << FnName << PointeeTy
4894 << Call->getCallee()->getSourceRange());
4895 else
4896 continue;
4897
4898 DiagRuntimeBehavior(
4899 Dest->getExprLoc(), Dest,
4900 PDiag(diag::note_bad_memaccess_silence)
4901 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4902 break;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004903 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004904
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004905}
4906
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004907// A little helper routine: ignore addition and subtraction of integer literals.
4908// This intentionally does not ignore all integer constant expressions because
4909// we don't want to remove sizeof().
4910static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4911 Ex = Ex->IgnoreParenCasts();
4912
4913 for (;;) {
4914 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4915 if (!BO || !BO->isAdditiveOp())
4916 break;
4917
4918 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4919 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4920
4921 if (isa<IntegerLiteral>(RHS))
4922 Ex = LHS;
4923 else if (isa<IntegerLiteral>(LHS))
4924 Ex = RHS;
4925 else
4926 break;
4927 }
4928
4929 return Ex;
4930}
4931
Anna Zaks0f38ace2012-08-08 21:42:23 +00004932static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4933 ASTContext &Context) {
4934 // Only handle constant-sized or VLAs, but not flexible members.
4935 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4936 // Only issue the FIXIT for arrays of size > 1.
4937 if (CAT->getSize().getSExtValue() <= 1)
4938 return false;
4939 } else if (!Ty->isVariableArrayType()) {
4940 return false;
4941 }
4942 return true;
4943}
4944
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004945// Warn if the user has made the 'size' argument to strlcpy or strlcat
4946// be the size of the source, instead of the destination.
4947void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4948 IdentifierInfo *FnName) {
4949
4950 // Don't crash if the user has the wrong number of arguments
Stephen Hines176edba2014-12-01 14:53:08 -08004951 unsigned NumArgs = Call->getNumArgs();
4952 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004953 return;
4954
4955 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4956 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004957 const Expr *CompareWithSrc = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004958
4959 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4960 Call->getLocStart(), Call->getRParenLoc()))
4961 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004962
4963 // Look for 'strlcpy(dst, x, sizeof(x))'
4964 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4965 CompareWithSrc = Ex;
4966 else {
4967 // Look for 'strlcpy(dst, x, strlen(x))'
4968 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004969 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4970 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004971 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4972 }
4973 }
4974
4975 if (!CompareWithSrc)
4976 return;
4977
4978 // Determine if the argument to sizeof/strlen is equal to the source
4979 // argument. In principle there's all kinds of things you could do
4980 // here, for instance creating an == expression and evaluating it with
4981 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4982 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4983 if (!SrcArgDRE)
4984 return;
4985
4986 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4987 if (!CompareWithSrcDRE ||
4988 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4989 return;
4990
4991 const Expr *OriginalSizeArg = Call->getArg(2);
4992 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4993 << OriginalSizeArg->getSourceRange() << FnName;
4994
4995 // Output a FIXIT hint if the destination is an array (rather than a
4996 // pointer to an array). This could be enhanced to handle some
4997 // pointers if we know the actual size, like if DstArg is 'array+2'
4998 // we could say 'sizeof(array)-2'.
4999 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00005000 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00005001 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00005002
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00005003 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00005004 llvm::raw_svector_ostream OS(sizeString);
5005 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005006 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00005007 OS << ")";
5008
5009 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5010 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5011 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00005012}
5013
Anna Zaksc36bedc2012-02-01 19:08:57 +00005014/// Check if two expressions refer to the same declaration.
5015static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5016 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5017 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5018 return D1->getDecl() == D2->getDecl();
5019 return false;
5020}
5021
5022static const Expr *getStrlenExprArg(const Expr *E) {
5023 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5024 const FunctionDecl *FD = CE->getDirectCallee();
5025 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005026 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005027 return CE->getArg(0)->IgnoreParenCasts();
5028 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005029 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005030}
5031
5032// Warn on anti-patterns as the 'size' argument to strncat.
5033// The correct size argument should look like following:
5034// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5035void Sema::CheckStrncatArguments(const CallExpr *CE,
5036 IdentifierInfo *FnName) {
5037 // Don't crash if the user has the wrong number of arguments.
5038 if (CE->getNumArgs() < 3)
5039 return;
5040 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5041 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5042 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5043
Stephen Hines651f13c2014-04-23 16:59:28 -07005044 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5045 CE->getRParenLoc()))
5046 return;
5047
Anna Zaksc36bedc2012-02-01 19:08:57 +00005048 // Identify common expressions, which are wrongly used as the size argument
5049 // to strncat and may lead to buffer overflows.
5050 unsigned PatternType = 0;
5051 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5052 // - sizeof(dst)
5053 if (referToTheSameDecl(SizeOfArg, DstArg))
5054 PatternType = 1;
5055 // - sizeof(src)
5056 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5057 PatternType = 2;
5058 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5059 if (BE->getOpcode() == BO_Sub) {
5060 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5061 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5062 // - sizeof(dst) - strlen(dst)
5063 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5064 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5065 PatternType = 1;
5066 // - sizeof(src) - (anything)
5067 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5068 PatternType = 2;
5069 }
5070 }
5071
5072 if (PatternType == 0)
5073 return;
5074
Anna Zaksafdb0412012-02-03 01:27:37 +00005075 // Generate the diagnostic.
5076 SourceLocation SL = LenArg->getLocStart();
5077 SourceRange SR = LenArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005078 SourceManager &SM = getSourceManager();
Anna Zaksafdb0412012-02-03 01:27:37 +00005079
5080 // If the function is defined as a builtin macro, do not show macro expansion.
5081 if (SM.isMacroArgExpansion(SL)) {
5082 SL = SM.getSpellingLoc(SL);
5083 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5084 SM.getSpellingLoc(SR.getEnd()));
5085 }
5086
Anna Zaks0f38ace2012-08-08 21:42:23 +00005087 // Check if the destination is an array (rather than a pointer to an array).
5088 QualType DstTy = DstArg->getType();
5089 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5090 Context);
5091 if (!isKnownSizeArray) {
5092 if (PatternType == 1)
5093 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5094 else
5095 Diag(SL, diag::warn_strncat_src_size) << SR;
5096 return;
5097 }
5098
Anna Zaksc36bedc2012-02-01 19:08:57 +00005099 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00005100 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005101 else
Anna Zaksafdb0412012-02-03 01:27:37 +00005102 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005103
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00005104 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005105 llvm::raw_svector_ostream OS(sizeString);
5106 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005107 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005108 OS << ") - ";
5109 OS << "strlen(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005110 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005111 OS << ") - 1";
5112
Anna Zaksafdb0412012-02-03 01:27:37 +00005113 Diag(SL, diag::note_strncat_wrong_size)
5114 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005115}
5116
Ted Kremenek06de2762007-08-17 16:46:58 +00005117//===--- CHECK: Return Address of Stack Variable --------------------------===//
5118
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005119static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5120 Decl *ParentDecl);
5121static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5122 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005123
5124/// CheckReturnStackAddr - Check if a return statement returns the address
5125/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07005126static void
5127CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5128 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005129
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005130 Expr *stackE = nullptr;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005131 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005132
5133 // Perform checking for returned stack addresses, local blocks,
5134 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00005135 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07005136 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005137 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005138 } else if (lhsType->isReferenceType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005139 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005140 }
5141
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005142 if (!stackE)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005143 return; // Nothing suspicious was found.
5144
5145 SourceLocation diagLoc;
5146 SourceRange diagRange;
5147 if (refVars.empty()) {
5148 diagLoc = stackE->getLocStart();
5149 diagRange = stackE->getSourceRange();
5150 } else {
5151 // We followed through a reference variable. 'stackE' contains the
5152 // problematic expression but we will warn at the return statement pointing
5153 // at the reference variable. We will later display the "trail" of
5154 // reference variables using notes.
5155 diagLoc = refVars[0]->getLocStart();
5156 diagRange = refVars[0]->getSourceRange();
5157 }
5158
5159 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07005160 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005161 : diag::warn_ret_stack_addr)
5162 << DR->getDecl()->getDeclName() << diagRange;
5163 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07005164 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005165 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07005166 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005167 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07005168 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5169 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005170 << diagRange;
5171 }
5172
5173 // Display the "trail" of reference variables that we followed until we
5174 // found the problematic expression using notes.
5175 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5176 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5177 // If this var binds to another reference var, show the range of the next
5178 // var, otherwise the var binds to the problematic expression, in which case
5179 // show the range of the expression.
5180 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5181 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07005182 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5183 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00005184 }
5185}
5186
5187/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5188/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005189/// to a location on the stack, a local block, an address of a label, or a
5190/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00005191/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005192/// encounter a subexpression that (1) clearly does not lead to one of the
5193/// above problematic expressions (2) is something we cannot determine leads to
5194/// a problematic expression based on such local checking.
5195///
5196/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5197/// the expression that they point to. Such variables are added to the
5198/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00005199///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005200/// EvalAddr processes expressions that are pointers that are used as
5201/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005202/// At the base case of the recursion is a check for the above problematic
5203/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00005204///
5205/// This implementation handles:
5206///
5207/// * pointer-to-pointer casts
5208/// * implicit conversions from array references to pointers
5209/// * taking the address of fields
5210/// * arbitrary interplay between "&" and "*" operators
5211/// * pointer arithmetic from an address of a stack variable
5212/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005213static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5214 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005215 if (E->isTypeDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005216 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005217
Ted Kremenek06de2762007-08-17 16:46:58 +00005218 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00005219 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00005220 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005221 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005222 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Peter Collingbournef111d932011-04-15 00:35:48 +00005224 E = E->IgnoreParens();
5225
Ted Kremenek06de2762007-08-17 16:46:58 +00005226 // Our "symbolic interpreter" is just a dispatch off the currently
5227 // viewed AST node. We then recursively traverse the AST by calling
5228 // EvalAddr and EvalVal appropriately.
5229 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005230 case Stmt::DeclRefExprClass: {
5231 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5232
Stephen Hines651f13c2014-04-23 16:59:28 -07005233 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005234 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005235 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005236
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005237 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5238 // If this is a reference variable, follow through to the expression that
5239 // it points to.
5240 if (V->hasLocalStorage() &&
5241 V->getType()->isReferenceType() && V->hasInit()) {
5242 // Add the reference variable to the "trail".
5243 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005244 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005245 }
5246
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005247 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005248 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005249
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005250 case Stmt::UnaryOperatorClass: {
5251 // The only unary operator that make sense to handle here
5252 // is AddrOf. All others don't make sense as pointers.
5253 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005254
John McCall2de56d12010-08-25 11:45:40 +00005255 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005256 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005257 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005258 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005259 }
Mike Stump1eb44332009-09-09 15:08:12 +00005260
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005261 case Stmt::BinaryOperatorClass: {
5262 // Handle pointer arithmetic. All other binary operators are not valid
5263 // in this context.
5264 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00005265 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00005266
John McCall2de56d12010-08-25 11:45:40 +00005267 if (op != BO_Add && op != BO_Sub)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005268 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005270 Expr *Base = B->getLHS();
5271
5272 // Determine which argument is the real pointer base. It could be
5273 // the RHS argument instead of the LHS.
5274 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00005275
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005276 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005277 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005278 }
Steve Naroff61f40a22008-09-10 19:17:48 +00005279
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005280 // For conditional operators we need to see if either the LHS or RHS are
5281 // valid DeclRefExpr*s. If one of them is valid, we return it.
5282 case Stmt::ConditionalOperatorClass: {
5283 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005285 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005286 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5287 if (Expr *LHSExpr = C->getLHS()) {
5288 // In C++, we can have a throw-expression, which has 'void' type.
5289 if (!LHSExpr->getType()->isVoidType())
5290 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005291 return LHS;
5292 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005293
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005294 // In C++, we can have a throw-expression, which has 'void' type.
5295 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005296 return nullptr;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005297
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005298 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005299 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005300
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005301 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00005302 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005303 return E; // local block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005304 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005305
5306 case Stmt::AddrLabelExprClass:
5307 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00005308
John McCall80ee6e82011-11-10 05:35:25 +00005309 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005310 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5311 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005312
Ted Kremenek54b52742008-08-07 00:49:01 +00005313 // For casts, we need to handle conversions from arrays to
5314 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00005315 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00005316 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005317 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00005318 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00005319 case Stmt::CXXStaticCastExprClass:
5320 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00005321 case Stmt::CXXConstCastExprClass:
5322 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005323 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5324 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005325 case CK_LValueToRValue:
5326 case CK_NoOp:
5327 case CK_BaseToDerived:
5328 case CK_DerivedToBase:
5329 case CK_UncheckedDerivedToBase:
5330 case CK_Dynamic:
5331 case CK_CPointerToObjCPointerCast:
5332 case CK_BlockPointerToObjCPointerCast:
5333 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005334 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005335
5336 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005337 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005338
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005339 case CK_BitCast:
5340 if (SubExpr->getType()->isAnyPointerType() ||
5341 SubExpr->getType()->isBlockPointerType() ||
5342 SubExpr->getType()->isObjCQualifiedIdType())
5343 return EvalAddr(SubExpr, refVars, ParentDecl);
5344 else
5345 return nullptr;
5346
Eli Friedman8b9414e2012-02-23 23:04:32 +00005347 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005348 return nullptr;
Eli Friedman8b9414e2012-02-23 23:04:32 +00005349 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005350 }
Mike Stump1eb44332009-09-09 15:08:12 +00005351
Douglas Gregor03e80032011-06-21 17:03:29 +00005352 case Stmt::MaterializeTemporaryExprClass:
5353 if (Expr *Result = EvalAddr(
5354 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005355 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005356 return Result;
5357
5358 return E;
5359
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005360 // Everything else: we simply don't reason about them.
5361 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005362 return nullptr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005363 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005364}
Mike Stump1eb44332009-09-09 15:08:12 +00005365
Ted Kremenek06de2762007-08-17 16:46:58 +00005366
5367/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5368/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005369static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5370 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005371do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005372 // We should only be called for evaluating non-pointer expressions, or
5373 // expressions with a pointer type that are not used as references but instead
5374 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Ted Kremenek06de2762007-08-17 16:46:58 +00005376 // Our "symbolic interpreter" is just a dispatch off the currently
5377 // viewed AST node. We then recursively traverse the AST by calling
5378 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00005379
5380 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00005381 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005382 case Stmt::ImplicitCastExprClass: {
5383 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00005384 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005385 E = IE->getSubExpr();
5386 continue;
5387 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005388 return nullptr;
Ted Kremenek68957a92010-08-04 20:01:07 +00005389 }
5390
John McCall80ee6e82011-11-10 05:35:25 +00005391 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005392 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005393
Douglas Gregora2813ce2009-10-23 18:54:35 +00005394 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005395 // When we hit a DeclRefExpr we are looking at code that refers to a
5396 // variable's name. If it's not a reference variable we check if it has
5397 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00005398 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Stephen Hines651f13c2014-04-23 16:59:28 -07005400 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005401 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005402 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005403
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005404 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5405 // Check if it refers to itself, e.g. "int& i = i;".
5406 if (V == ParentDecl)
5407 return DR;
5408
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005409 if (V->hasLocalStorage()) {
5410 if (!V->getType()->isReferenceType())
5411 return DR;
5412
5413 // Reference variable, follow through to the expression that
5414 // it points to.
5415 if (V->hasInit()) {
5416 // Add the reference variable to the "trail".
5417 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005418 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005419 }
5420 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005421 }
Mike Stump1eb44332009-09-09 15:08:12 +00005422
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005423 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005424 }
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Ted Kremenek06de2762007-08-17 16:46:58 +00005426 case Stmt::UnaryOperatorClass: {
5427 // The only unary operator that make sense to handle here
5428 // is Deref. All others don't resolve to a "name." This includes
5429 // handling all sorts of rvalues passed to a unary operator.
5430 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005431
John McCall2de56d12010-08-25 11:45:40 +00005432 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005433 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005434
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005435 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005436 }
Mike Stump1eb44332009-09-09 15:08:12 +00005437
Ted Kremenek06de2762007-08-17 16:46:58 +00005438 case Stmt::ArraySubscriptExprClass: {
5439 // Array subscripts are potential references to data on the stack. We
5440 // retrieve the DeclRefExpr* for the array variable if it indeed
5441 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005442 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005443 }
Mike Stump1eb44332009-09-09 15:08:12 +00005444
Ted Kremenek06de2762007-08-17 16:46:58 +00005445 case Stmt::ConditionalOperatorClass: {
5446 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005447 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00005448 ConditionalOperator *C = cast<ConditionalOperator>(E);
5449
Anders Carlsson39073232007-11-30 19:04:31 +00005450 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005451 if (Expr *LHSExpr = C->getLHS()) {
5452 // In C++, we can have a throw-expression, which has 'void' type.
5453 if (!LHSExpr->getType()->isVoidType())
5454 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5455 return LHS;
5456 }
5457
5458 // In C++, we can have a throw-expression, which has 'void' type.
5459 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005460 return nullptr;
Anders Carlsson39073232007-11-30 19:04:31 +00005461
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005462 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005463 }
Mike Stump1eb44332009-09-09 15:08:12 +00005464
Ted Kremenek06de2762007-08-17 16:46:58 +00005465 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00005466 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00005467 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005468
Ted Kremenek06de2762007-08-17 16:46:58 +00005469 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00005470 if (M->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005471 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005472
5473 // Check whether the member type is itself a reference, in which case
5474 // we're not going to refer to the member, but to what the member refers to.
5475 if (M->getMemberDecl()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005476 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005477
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005478 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005479 }
Mike Stump1eb44332009-09-09 15:08:12 +00005480
Douglas Gregor03e80032011-06-21 17:03:29 +00005481 case Stmt::MaterializeTemporaryExprClass:
5482 if (Expr *Result = EvalVal(
5483 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005484 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005485 return Result;
5486
5487 return E;
5488
Ted Kremenek06de2762007-08-17 16:46:58 +00005489 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005490 // Check that we don't return or take the address of a reference to a
5491 // temporary. This is only useful in C++.
5492 if (!E->isTypeDependent() && E->isRValue())
5493 return E;
5494
5495 // Everything else: we simply don't reason about them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005496 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005497 }
Ted Kremenek68957a92010-08-04 20:01:07 +00005498} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00005499}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005500
Stephen Hines651f13c2014-04-23 16:59:28 -07005501void
5502Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5503 SourceLocation ReturnLoc,
5504 bool isObjCMethod,
5505 const AttrVec *Attrs,
5506 const FunctionDecl *FD) {
5507 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5508
5509 // Check if the return value is null but should not be.
5510 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5511 CheckNonNullExpr(*this, RetValExp))
5512 Diag(ReturnLoc, diag::warn_null_ret)
5513 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5514
5515 // C++11 [basic.stc.dynamic.allocation]p4:
5516 // If an allocation function declared with a non-throwing
5517 // exception-specification fails to allocate storage, it shall return
5518 // a null pointer. Any other allocation function that fails to allocate
5519 // storage shall indicate failure only by throwing an exception [...]
5520 if (FD) {
5521 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5522 if (Op == OO_New || Op == OO_Array_New) {
5523 const FunctionProtoType *Proto
5524 = FD->getType()->castAs<FunctionProtoType>();
5525 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5526 CheckNonNullExpr(*this, RetValExp))
5527 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5528 << FD << getLangOpts().CPlusPlus11;
5529 }
5530 }
5531}
5532
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005533//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5534
5535/// Check for comparisons of floating point operands using != and ==.
5536/// Issue a warning if these are no self-comparisons, as they are not likely
5537/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00005538void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00005539 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5540 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005541
5542 // Special case: check for x == x (which is OK).
5543 // Do not emit warnings for such cases.
5544 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5545 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5546 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00005547 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005548
5549
Ted Kremenek1b500bb2007-11-29 00:59:04 +00005550 // Special case: check for comparisons against literals that can be exactly
5551 // represented by APFloat. In such cases, do not emit a warning. This
5552 // is a heuristic: often comparison against such literals are used to
5553 // detect if a value in a variable has not changed. This clearly can
5554 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00005555 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5556 if (FLL->isExact())
5557 return;
5558 } else
5559 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5560 if (FLR->isExact())
5561 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005562
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005563 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00005564 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005565 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005566 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005567
David Blaikie980343b2012-07-16 20:47:22 +00005568 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005569 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005570 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005571
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005572 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00005573 Diag(Loc, diag::warn_floatingpoint_eq)
5574 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005575}
John McCallba26e582010-01-04 23:21:16 +00005576
John McCallf2370c92010-01-06 05:24:50 +00005577//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5578//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00005579
John McCallf2370c92010-01-06 05:24:50 +00005580namespace {
John McCallba26e582010-01-04 23:21:16 +00005581
John McCallf2370c92010-01-06 05:24:50 +00005582/// Structure recording the 'active' range of an integer-valued
5583/// expression.
5584struct IntRange {
5585 /// The number of bits active in the int.
5586 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00005587
John McCallf2370c92010-01-06 05:24:50 +00005588 /// True if the int is known not to have negative values.
5589 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00005590
John McCallf2370c92010-01-06 05:24:50 +00005591 IntRange(unsigned Width, bool NonNegative)
5592 : Width(Width), NonNegative(NonNegative)
5593 {}
John McCallba26e582010-01-04 23:21:16 +00005594
John McCall1844a6e2010-11-10 23:38:19 +00005595 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00005596 static IntRange forBoolType() {
5597 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00005598 }
5599
John McCall1844a6e2010-11-10 23:38:19 +00005600 /// Returns the range of an opaque value of the given integral type.
5601 static IntRange forValueOfType(ASTContext &C, QualType T) {
5602 return forValueOfCanonicalType(C,
5603 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00005604 }
5605
John McCall1844a6e2010-11-10 23:38:19 +00005606 /// Returns the range of an opaque value of a canonical integral type.
5607 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00005608 assert(T->isCanonicalUnqualified());
5609
5610 if (const VectorType *VT = dyn_cast<VectorType>(T))
5611 T = VT->getElementType().getTypePtr();
5612 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5613 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005614 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5615 T = AT->getValueType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00005616
David Majnemerf9eaf982013-06-07 22:07:20 +00005617 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00005618 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00005619 EnumDecl *Enum = ET->getDecl();
5620 if (!Enum->isCompleteDefinition())
5621 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00005622
David Majnemerf9eaf982013-06-07 22:07:20 +00005623 unsigned NumPositive = Enum->getNumPositiveBits();
5624 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00005625
David Majnemerf9eaf982013-06-07 22:07:20 +00005626 if (NumNegative == 0)
5627 return IntRange(NumPositive, true/*NonNegative*/);
5628 else
5629 return IntRange(std::max(NumPositive + 1, NumNegative),
5630 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00005631 }
John McCallf2370c92010-01-06 05:24:50 +00005632
5633 const BuiltinType *BT = cast<BuiltinType>(T);
5634 assert(BT->isInteger());
5635
5636 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5637 }
5638
John McCall1844a6e2010-11-10 23:38:19 +00005639 /// Returns the "target" range of a canonical integral type, i.e.
5640 /// the range of values expressible in the type.
5641 ///
5642 /// This matches forValueOfCanonicalType except that enums have the
5643 /// full range of their type, not the range of their enumerators.
5644 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5645 assert(T->isCanonicalUnqualified());
5646
5647 if (const VectorType *VT = dyn_cast<VectorType>(T))
5648 T = VT->getElementType().getTypePtr();
5649 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5650 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005651 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5652 T = AT->getValueType().getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005653 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00005654 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005655
5656 const BuiltinType *BT = cast<BuiltinType>(T);
5657 assert(BT->isInteger());
5658
5659 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5660 }
5661
5662 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005663 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00005664 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00005665 L.NonNegative && R.NonNegative);
5666 }
5667
John McCall1844a6e2010-11-10 23:38:19 +00005668 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005669 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00005670 return IntRange(std::min(L.Width, R.Width),
5671 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00005672 }
5673};
5674
Ted Kremenek0692a192012-01-31 05:37:37 +00005675static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5676 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005677 if (value.isSigned() && value.isNegative())
5678 return IntRange(value.getMinSignedBits(), false);
5679
5680 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00005681 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005682
5683 // isNonNegative() just checks the sign bit without considering
5684 // signedness.
5685 return IntRange(value.getActiveBits(), true);
5686}
5687
Ted Kremenek0692a192012-01-31 05:37:37 +00005688static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5689 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005690 if (result.isInt())
5691 return GetValueRange(C, result.getInt(), MaxWidth);
5692
5693 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00005694 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5695 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5696 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5697 R = IntRange::join(R, El);
5698 }
John McCallf2370c92010-01-06 05:24:50 +00005699 return R;
5700 }
5701
5702 if (result.isComplexInt()) {
5703 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5704 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5705 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00005706 }
5707
5708 // This can happen with lossless casts to intptr_t of "based" lvalues.
5709 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00005710 // FIXME: The only reason we need to pass the type in here is to get
5711 // the sign right on this one case. It would be nice if APValue
5712 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00005713 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005714 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00005715}
John McCallf2370c92010-01-06 05:24:50 +00005716
Eli Friedman09bddcf2013-07-08 20:20:06 +00005717static QualType GetExprType(Expr *E) {
5718 QualType Ty = E->getType();
5719 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5720 Ty = AtomicRHS->getValueType();
5721 return Ty;
5722}
5723
John McCallf2370c92010-01-06 05:24:50 +00005724/// Pseudo-evaluate the given integer expression, estimating the
5725/// range of values it might take.
5726///
5727/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00005728static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005729 E = E->IgnoreParens();
5730
5731 // Try a full evaluation first.
5732 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005733 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00005734 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005735
5736 // I think we only want to look through implicit casts here; if the
5737 // user has an explicit widening cast, we should treat the value as
5738 // being of the new, wider type.
5739 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00005740 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00005741 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5742
Eli Friedman09bddcf2013-07-08 20:20:06 +00005743 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00005744
John McCall2de56d12010-08-25 11:45:40 +00005745 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00005746
John McCallf2370c92010-01-06 05:24:50 +00005747 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00005748 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00005749 return OutputTypeRange;
5750
5751 IntRange SubRange
5752 = GetExprRange(C, CE->getSubExpr(),
5753 std::min(MaxWidth, OutputTypeRange.Width));
5754
5755 // Bail out if the subexpr's range is as wide as the cast type.
5756 if (SubRange.Width >= OutputTypeRange.Width)
5757 return OutputTypeRange;
5758
5759 // Otherwise, we take the smaller width, and we're non-negative if
5760 // either the output type or the subexpr is.
5761 return IntRange(SubRange.Width,
5762 SubRange.NonNegative || OutputTypeRange.NonNegative);
5763 }
5764
5765 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5766 // If we can fold the condition, just take that operand.
5767 bool CondResult;
5768 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5769 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5770 : CO->getFalseExpr(),
5771 MaxWidth);
5772
5773 // Otherwise, conservatively merge.
5774 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5775 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5776 return IntRange::join(L, R);
5777 }
5778
5779 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5780 switch (BO->getOpcode()) {
5781
5782 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005783 case BO_LAnd:
5784 case BO_LOr:
5785 case BO_LT:
5786 case BO_GT:
5787 case BO_LE:
5788 case BO_GE:
5789 case BO_EQ:
5790 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005791 return IntRange::forBoolType();
5792
John McCall862ff872011-07-13 06:35:24 +00005793 // The type of the assignments is the type of the LHS, so the RHS
5794 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005795 case BO_MulAssign:
5796 case BO_DivAssign:
5797 case BO_RemAssign:
5798 case BO_AddAssign:
5799 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005800 case BO_XorAssign:
5801 case BO_OrAssign:
5802 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005803 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005804
John McCall862ff872011-07-13 06:35:24 +00005805 // Simple assignments just pass through the RHS, which will have
5806 // been coerced to the LHS type.
5807 case BO_Assign:
5808 // TODO: bitfields?
5809 return GetExprRange(C, BO->getRHS(), MaxWidth);
5810
John McCallf2370c92010-01-06 05:24:50 +00005811 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005812 case BO_PtrMemD:
5813 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005814 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005815
John McCall60fad452010-01-06 22:07:33 +00005816 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005817 case BO_And:
5818 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005819 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5820 GetExprRange(C, BO->getRHS(), MaxWidth));
5821
John McCallf2370c92010-01-06 05:24:50 +00005822 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005823 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005824 // ...except that we want to treat '1 << (blah)' as logically
5825 // positive. It's an important idiom.
5826 if (IntegerLiteral *I
5827 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5828 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005829 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005830 return IntRange(R.Width, /*NonNegative*/ true);
5831 }
5832 }
5833 // fallthrough
5834
John McCall2de56d12010-08-25 11:45:40 +00005835 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005836 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005837
John McCall60fad452010-01-06 22:07:33 +00005838 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005839 case BO_Shr:
5840 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005841 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5842
5843 // If the shift amount is a positive constant, drop the width by
5844 // that much.
5845 llvm::APSInt shift;
5846 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5847 shift.isNonNegative()) {
5848 unsigned zext = shift.getZExtValue();
5849 if (zext >= L.Width)
5850 L.Width = (L.NonNegative ? 0 : 1);
5851 else
5852 L.Width -= zext;
5853 }
5854
5855 return L;
5856 }
5857
5858 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005859 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005860 return GetExprRange(C, BO->getRHS(), MaxWidth);
5861
John McCall60fad452010-01-06 22:07:33 +00005862 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005863 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005864 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005865 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005866 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005867
John McCall00fe7612011-07-14 22:39:48 +00005868 // The width of a division result is mostly determined by the size
5869 // of the LHS.
5870 case BO_Div: {
5871 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005872 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005873 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5874
5875 // If the divisor is constant, use that.
5876 llvm::APSInt divisor;
5877 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5878 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5879 if (log2 >= L.Width)
5880 L.Width = (L.NonNegative ? 0 : 1);
5881 else
5882 L.Width = std::min(L.Width - log2, MaxWidth);
5883 return L;
5884 }
5885
5886 // Otherwise, just use the LHS's width.
5887 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5888 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5889 }
5890
5891 // The result of a remainder can't be larger than the result of
5892 // either side.
5893 case BO_Rem: {
5894 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005895 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005896 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5897 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5898
5899 IntRange meet = IntRange::meet(L, R);
5900 meet.Width = std::min(meet.Width, MaxWidth);
5901 return meet;
5902 }
5903
5904 // The default behavior is okay for these.
5905 case BO_Mul:
5906 case BO_Add:
5907 case BO_Xor:
5908 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005909 break;
5910 }
5911
John McCall00fe7612011-07-14 22:39:48 +00005912 // The default case is to treat the operation as if it were closed
5913 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005914 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5915 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5916 return IntRange::join(L, R);
5917 }
5918
5919 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5920 switch (UO->getOpcode()) {
5921 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005922 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005923 return IntRange::forBoolType();
5924
5925 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005926 case UO_Deref:
5927 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005928 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005929
5930 default:
5931 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5932 }
5933 }
5934
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005935 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5936 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5937
John McCall993f43f2013-05-06 21:39:12 +00005938 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005939 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005940 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005941
Eli Friedman09bddcf2013-07-08 20:20:06 +00005942 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005943}
John McCall51313c32010-01-04 23:31:57 +00005944
Ted Kremenek0692a192012-01-31 05:37:37 +00005945static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005946 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005947}
5948
John McCall51313c32010-01-04 23:31:57 +00005949/// Checks whether the given value, which currently has the given
5950/// source semantics, has the same value when coerced through the
5951/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005952static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5953 const llvm::fltSemantics &Src,
5954 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005955 llvm::APFloat truncated = value;
5956
5957 bool ignored;
5958 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5959 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5960
5961 return truncated.bitwiseIsEqual(value);
5962}
5963
5964/// Checks whether the given value, which currently has the given
5965/// source semantics, has the same value when coerced through the
5966/// target semantics.
5967///
5968/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005969static bool IsSameFloatAfterCast(const APValue &value,
5970 const llvm::fltSemantics &Src,
5971 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005972 if (value.isFloat())
5973 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5974
5975 if (value.isVector()) {
5976 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5977 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5978 return false;
5979 return true;
5980 }
5981
5982 assert(value.isComplexFloat());
5983 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5984 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5985}
5986
Ted Kremenek0692a192012-01-31 05:37:37 +00005987static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005988
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005989static bool IsZero(Sema &S, Expr *E) {
5990 // Suppress cases where we are comparing against an enum constant.
5991 if (const DeclRefExpr *DR =
5992 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5993 if (isa<EnumConstantDecl>(DR->getDecl()))
5994 return false;
5995
5996 // Suppress cases where the '0' value is expanded from a macro.
5997 if (E->getLocStart().isMacroID())
5998 return false;
5999
John McCall323ed742010-05-06 08:58:33 +00006000 llvm::APSInt Value;
6001 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6002}
6003
John McCall372e1032010-10-06 00:25:24 +00006004static bool HasEnumType(Expr *E) {
6005 // Strip off implicit integral promotions.
6006 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00006007 if (ICE->getCastKind() != CK_IntegralCast &&
6008 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00006009 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00006010 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00006011 }
6012
6013 return E->getType()->isEnumeralType();
6014}
6015
Ted Kremenek0692a192012-01-31 05:37:37 +00006016static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00006017 // Disable warning in template instantiations.
6018 if (!S.ActiveTemplateInstantiations.empty())
6019 return;
6020
John McCall2de56d12010-08-25 11:45:40 +00006021 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00006022 if (E->isValueDependent())
6023 return;
6024
John McCall2de56d12010-08-25 11:45:40 +00006025 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00006026 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00006027 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00006028 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006029 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00006030 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00006031 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00006032 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006033 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00006034 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00006035 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00006036 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00006037 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00006038 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00006039 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00006040 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6041 }
6042}
6043
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006044static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006045 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006046 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006047 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00006048 // Disable warning in template instantiations.
6049 if (!S.ActiveTemplateInstantiations.empty())
6050 return;
6051
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006052 // TODO: Investigate using GetExprRange() to get tighter bounds
6053 // on the bit ranges.
6054 QualType OtherT = Other->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08006055 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
6056 OtherT = AT->getValueType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006057 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6058 unsigned OtherWidth = OtherRange.Width;
6059
6060 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6061
Richard Trieu526e6272012-11-14 22:50:24 +00006062 // 0 values are handled later by CheckTrivialUnsignedComparison().
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006063 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu526e6272012-11-14 22:50:24 +00006064 return;
6065
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006066 BinaryOperatorKind op = E->getOpcode();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006067 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00006068
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006069 // Used for diagnostic printout.
6070 enum {
6071 LiteralConstant = 0,
6072 CXXBoolLiteralTrue,
6073 CXXBoolLiteralFalse
6074 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00006075
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006076 if (!OtherIsBooleanType) {
6077 QualType ConstantT = Constant->getType();
6078 QualType CommonT = E->getLHS()->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00006079
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006080 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6081 return;
6082 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6083 "comparison with non-integer type");
6084
6085 bool ConstantSigned = ConstantT->isSignedIntegerType();
6086 bool CommonSigned = CommonT->isSignedIntegerType();
6087
6088 bool EqualityOnly = false;
6089
6090 if (CommonSigned) {
6091 // The common type is signed, therefore no signed to unsigned conversion.
6092 if (!OtherRange.NonNegative) {
6093 // Check that the constant is representable in type OtherT.
6094 if (ConstantSigned) {
6095 if (OtherWidth >= Value.getMinSignedBits())
6096 return;
6097 } else { // !ConstantSigned
6098 if (OtherWidth >= Value.getActiveBits() + 1)
6099 return;
6100 }
6101 } else { // !OtherSigned
6102 // Check that the constant is representable in type OtherT.
6103 // Negative values are out of range.
6104 if (ConstantSigned) {
6105 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6106 return;
6107 } else { // !ConstantSigned
6108 if (OtherWidth >= Value.getActiveBits())
6109 return;
6110 }
Richard Trieu526e6272012-11-14 22:50:24 +00006111 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006112 } else { // !CommonSigned
6113 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00006114 if (OtherWidth >= Value.getActiveBits())
6115 return;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006116 } else { // OtherSigned
6117 assert(!ConstantSigned &&
6118 "Two signed types converted to unsigned types.");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006119 // Check to see if the constant is representable in OtherT.
6120 if (OtherWidth > Value.getActiveBits())
6121 return;
6122 // Check to see if the constant is equivalent to a negative value
6123 // cast to CommonT.
6124 if (S.Context.getIntWidth(ConstantT) ==
6125 S.Context.getIntWidth(CommonT) &&
6126 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6127 return;
6128 // The constant value rests between values that OtherT can represent
6129 // after conversion. Relational comparison still works, but equality
6130 // comparisons will be tautological.
6131 EqualityOnly = true;
Richard Trieu526e6272012-11-14 22:50:24 +00006132 }
6133 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006134
6135 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6136
6137 if (op == BO_EQ || op == BO_NE) {
6138 IsTrue = op == BO_NE;
6139 } else if (EqualityOnly) {
6140 return;
6141 } else if (RhsConstant) {
6142 if (op == BO_GT || op == BO_GE)
6143 IsTrue = !PositiveConstant;
6144 else // op == BO_LT || op == BO_LE
6145 IsTrue = PositiveConstant;
6146 } else {
6147 if (op == BO_LT || op == BO_LE)
6148 IsTrue = !PositiveConstant;
6149 else // op == BO_GT || op == BO_GE
6150 IsTrue = PositiveConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00006151 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006152 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006153 // Other isKnownToHaveBooleanValue
6154 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6155 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6156 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6157
6158 static const struct LinkedConditions {
6159 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6160 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6161 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6162 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6163 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6164 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6165
6166 } TruthTable = {
6167 // Constant on LHS. | Constant on RHS. |
6168 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6169 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6170 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6171 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6172 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6173 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6174 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6175 };
6176
6177 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6178
6179 enum ConstantValue ConstVal = Zero;
6180 if (Value.isUnsigned() || Value.isNonNegative()) {
6181 if (Value == 0) {
6182 LiteralOrBoolConstant =
6183 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6184 ConstVal = Zero;
6185 } else if (Value == 1) {
6186 LiteralOrBoolConstant =
6187 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6188 ConstVal = One;
6189 } else {
6190 LiteralOrBoolConstant = LiteralConstant;
6191 ConstVal = GT_One;
6192 }
6193 } else {
6194 ConstVal = LT_Zero;
6195 }
6196
6197 CompareBoolWithConstantResult CmpRes;
6198
6199 switch (op) {
6200 case BO_LT:
6201 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6202 break;
6203 case BO_GT:
6204 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6205 break;
6206 case BO_LE:
6207 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6208 break;
6209 case BO_GE:
6210 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6211 break;
6212 case BO_EQ:
6213 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6214 break;
6215 case BO_NE:
6216 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6217 break;
6218 default:
6219 CmpRes = Unkwn;
6220 break;
6221 }
6222
6223 if (CmpRes == AFals) {
6224 IsTrue = false;
6225 } else if (CmpRes == ATrue) {
6226 IsTrue = true;
6227 } else {
6228 return;
6229 }
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006230 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006231
6232 // If this is a comparison to an enum constant, include that
6233 // constant in the diagnostic.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006234 const EnumConstantDecl *ED = nullptr;
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006235 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6236 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6237
6238 SmallString<64> PrettySourceValue;
6239 llvm::raw_svector_ostream OS(PrettySourceValue);
6240 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00006241 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006242 else
6243 OS << Value;
6244
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006245 S.DiagRuntimeBehavior(
6246 E->getOperatorLoc(), E,
6247 S.PDiag(diag::warn_out_of_range_compare)
6248 << OS.str() << LiteralOrBoolConstant
6249 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6250 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006251}
6252
John McCall323ed742010-05-06 08:58:33 +00006253/// Analyze the operands of the given comparison. Implements the
6254/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00006255static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00006256 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6257 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00006258}
John McCall51313c32010-01-04 23:31:57 +00006259
John McCallba26e582010-01-04 23:21:16 +00006260/// \brief Implements -Wsign-compare.
6261///
Richard Trieudd225092011-09-15 21:56:47 +00006262/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00006263static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00006264 // The type the comparison is being performed in.
6265 QualType T = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08006266
6267 // Only analyze comparison operators where both sides have been converted to
6268 // the same type.
6269 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6270 return AnalyzeImpConvsInComparison(S, E);
6271
6272 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00006273 if (E->isValueDependent())
6274 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006275
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006276 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6277 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006278
6279 bool IsComparisonConstant = false;
6280
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006281 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006282 // of 'true' or 'false'.
6283 if (T->isIntegralType(S.Context)) {
6284 llvm::APSInt RHSValue;
6285 bool IsRHSIntegralLiteral =
6286 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6287 llvm::APSInt LHSValue;
6288 bool IsLHSIntegralLiteral =
6289 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6290 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6291 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6292 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6293 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6294 else
6295 IsComparisonConstant =
6296 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006297 } else if (!T->hasUnsignedIntegerRepresentation())
6298 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006299
John McCall323ed742010-05-06 08:58:33 +00006300 // We don't do anything special if this isn't an unsigned integral
6301 // comparison: we're only interested in integral comparisons, and
6302 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00006303 //
6304 // We also don't care about value-dependent expressions or expressions
6305 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006306 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00006307 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006308
John McCall323ed742010-05-06 08:58:33 +00006309 // Check to see if one of the (unmodified) operands is of different
6310 // signedness.
6311 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00006312 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6313 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00006314 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00006315 signedOperand = LHS;
6316 unsignedOperand = RHS;
6317 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6318 signedOperand = RHS;
6319 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00006320 } else {
John McCall323ed742010-05-06 08:58:33 +00006321 CheckTrivialUnsignedComparison(S, E);
6322 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006323 }
6324
John McCall323ed742010-05-06 08:58:33 +00006325 // Otherwise, calculate the effective range of the signed operand.
6326 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00006327
John McCall323ed742010-05-06 08:58:33 +00006328 // Go ahead and analyze implicit conversions in the operands. Note
6329 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00006330 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6331 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00006332
John McCall323ed742010-05-06 08:58:33 +00006333 // If the signed range is non-negative, -Wsign-compare won't fire,
6334 // but we should still check for comparisons which are always true
6335 // or false.
6336 if (signedRange.NonNegative)
6337 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006338
6339 // For (in)equality comparisons, if the unsigned operand is a
6340 // constant which cannot collide with a overflowed signed operand,
6341 // then reinterpreting the signed operand as unsigned will not
6342 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00006343 if (E->isEqualityOp()) {
6344 unsigned comparisonWidth = S.Context.getIntWidth(T);
6345 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00006346
John McCall323ed742010-05-06 08:58:33 +00006347 // We should never be unable to prove that the unsigned operand is
6348 // non-negative.
6349 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6350
6351 if (unsignedRange.Width < comparisonWidth)
6352 return;
6353 }
6354
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00006355 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6356 S.PDiag(diag::warn_mixed_sign_comparison)
6357 << LHS->getType() << RHS->getType()
6358 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00006359}
6360
John McCall15d7d122010-11-11 03:21:53 +00006361/// Analyzes an attempt to assign the given value to a bitfield.
6362///
6363/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00006364static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6365 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00006366 assert(Bitfield->isBitField());
6367 if (Bitfield->isInvalidDecl())
6368 return false;
6369
John McCall91b60142010-11-11 05:33:51 +00006370 // White-list bool bitfields.
6371 if (Bitfield->getType()->isBooleanType())
6372 return false;
6373
Douglas Gregor46ff3032011-02-04 13:09:01 +00006374 // Ignore value- or type-dependent expressions.
6375 if (Bitfield->getBitWidth()->isValueDependent() ||
6376 Bitfield->getBitWidth()->isTypeDependent() ||
6377 Init->isValueDependent() ||
6378 Init->isTypeDependent())
6379 return false;
6380
John McCall15d7d122010-11-11 03:21:53 +00006381 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6382
Richard Smith80d4b552011-12-28 19:48:30 +00006383 llvm::APSInt Value;
6384 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00006385 return false;
6386
John McCall15d7d122010-11-11 03:21:53 +00006387 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006388 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00006389
6390 if (OriginalWidth <= FieldWidth)
6391 return false;
6392
Eli Friedman3a643af2012-01-26 23:11:39 +00006393 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006394 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00006395 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00006396
Eli Friedman3a643af2012-01-26 23:11:39 +00006397 // Check whether the stored value is equal to the original value.
6398 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00006399 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00006400 return false;
6401
Eli Friedman3a643af2012-01-26 23:11:39 +00006402 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00006403 // therefore don't strictly fit into a signed bitfield of width 1.
6404 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00006405 return false;
6406
John McCall15d7d122010-11-11 03:21:53 +00006407 std::string PrettyValue = Value.toString(10);
6408 std::string PrettyTrunc = TruncatedValue.toString(10);
6409
6410 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6411 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6412 << Init->getSourceRange();
6413
6414 return true;
6415}
6416
John McCallbeb22aa2010-11-09 23:24:47 +00006417/// Analyze the given simple or compound assignment for warning-worthy
6418/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00006419static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00006420 // Just recurse on the LHS.
6421 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6422
6423 // We want to recurse on the RHS as normal unless we're assigning to
6424 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00006425 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006426 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00006427 E->getOperatorLoc())) {
6428 // Recurse, ignoring any implicit conversions on the RHS.
6429 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6430 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00006431 }
6432 }
6433
6434 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6435}
6436
John McCall51313c32010-01-04 23:31:57 +00006437/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006438static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006439 SourceLocation CContext, unsigned diag,
6440 bool pruneControlFlow = false) {
6441 if (pruneControlFlow) {
6442 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6443 S.PDiag(diag)
6444 << SourceType << T << E->getSourceRange()
6445 << SourceRange(CContext));
6446 return;
6447 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006448 S.Diag(E->getExprLoc(), diag)
6449 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6450}
6451
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006452/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006453static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006454 SourceLocation CContext, unsigned diag,
6455 bool pruneControlFlow = false) {
6456 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006457}
6458
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006459/// Diagnose an implicit cast from a literal expression. Does not warn when the
6460/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006461void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6462 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006463 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006464 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006465 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00006466 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6467 T->hasUnsignedIntegerRepresentation());
6468 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00006469 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006470 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00006471 return;
6472
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006473 // FIXME: Force the precision of the source value down so we don't print
6474 // digits which are usually useless (we don't really care here if we
6475 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6476 // would automatically print the shortest representation, but it's a bit
6477 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00006478 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006479 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6480 precision = (precision * 59 + 195) / 196;
6481 Value.toString(PrettySourceValue, precision);
6482
David Blaikiede7e7b82012-05-15 17:18:27 +00006483 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00006484 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6485 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6486 else
David Blaikiede7e7b82012-05-15 17:18:27 +00006487 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00006488
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006489 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00006490 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6491 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00006492}
6493
John McCall091f23f2010-11-09 22:22:12 +00006494std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6495 if (!Range.Width) return "0";
6496
6497 llvm::APSInt ValueInRange = Value;
6498 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00006499 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00006500 return ValueInRange.toString(10);
6501}
6502
Hans Wennborg88617a22012-08-28 15:44:30 +00006503static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6504 if (!isa<ImplicitCastExpr>(Ex))
6505 return false;
6506
6507 Expr *InnerE = Ex->IgnoreParenImpCasts();
6508 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6509 const Type *Source =
6510 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6511 if (Target->isDependentType())
6512 return false;
6513
6514 const BuiltinType *FloatCandidateBT =
6515 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6516 const Type *BoolCandidateType = ToBool ? Target : Source;
6517
6518 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6519 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6520}
6521
6522void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6523 SourceLocation CC) {
6524 unsigned NumArgs = TheCall->getNumArgs();
6525 for (unsigned i = 0; i < NumArgs; ++i) {
6526 Expr *CurrA = TheCall->getArg(i);
6527 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6528 continue;
6529
6530 bool IsSwapped = ((i > 0) &&
6531 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6532 IsSwapped |= ((i < (NumArgs - 1)) &&
6533 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6534 if (IsSwapped) {
6535 // Warn on this floating-point to bool conversion.
6536 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6537 CurrA->getType(), CC,
6538 diag::warn_impcast_floating_point_to_bool);
6539 }
6540 }
6541}
6542
Stephen Hines176edba2014-12-01 14:53:08 -08006543static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6544 SourceLocation CC) {
6545 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6546 E->getExprLoc()))
6547 return;
6548
6549 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6550 const Expr::NullPointerConstantKind NullKind =
6551 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6552 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6553 return;
6554
6555 // Return if target type is a safe conversion.
6556 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6557 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6558 return;
6559
6560 SourceLocation Loc = E->getSourceRange().getBegin();
6561
6562 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6563 if (NullKind == Expr::NPCK_GNUNull) {
6564 if (Loc.isMacroID())
6565 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6566 }
6567
6568 // Only warn if the null and context location are in the same macro expansion.
6569 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6570 return;
6571
6572 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6573 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6574 << FixItHint::CreateReplacement(Loc,
6575 S.getFixItZeroLiteralForType(T, Loc));
6576}
6577
John McCall323ed742010-05-06 08:58:33 +00006578void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006579 SourceLocation CC, bool *ICContext = nullptr) {
John McCall323ed742010-05-06 08:58:33 +00006580 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00006581
John McCall323ed742010-05-06 08:58:33 +00006582 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6583 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6584 if (Source == Target) return;
6585 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00006586
Chandler Carruth108f7562011-07-26 05:40:03 +00006587 // If the conversion context location is invalid don't complain. We also
6588 // don't want to emit a warning if the issue occurs from the expansion of
6589 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6590 // delay this check as long as possible. Once we detect we are in that
6591 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00006592 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00006593 return;
6594
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006595 // Diagnose implicit casts to bool.
6596 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6597 if (isa<StringLiteral>(E))
6598 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07006599 // and expressions, for instance, assert(0 && "error here"), are
6600 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006601 return DiagnoseImpCast(S, E, T, CC,
6602 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07006603 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6604 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6605 // This covers the literal expressions that evaluate to Objective-C
6606 // objects.
6607 return DiagnoseImpCast(S, E, T, CC,
6608 diag::warn_impcast_objective_c_literal_to_bool);
6609 }
6610 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6611 // Warn on pointer to bool conversion that is always true.
6612 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6613 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00006614 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006615 }
John McCall51313c32010-01-04 23:31:57 +00006616
6617 // Strip vector types.
6618 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006619 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006620 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006621 return;
John McCallb4eb64d2010-10-08 02:01:28 +00006622 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006623 }
Chris Lattnerb792b302011-06-14 04:51:15 +00006624
6625 // If the vector cast is cast between two vectors of the same size, it is
6626 // a bitcast, not a conversion.
6627 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6628 return;
John McCall51313c32010-01-04 23:31:57 +00006629
6630 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6631 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6632 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006633 if (auto VecTy = dyn_cast<VectorType>(Target))
6634 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00006635
6636 // Strip complex types.
6637 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006638 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006639 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006640 return;
6641
John McCallb4eb64d2010-10-08 02:01:28 +00006642 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006643 }
John McCall51313c32010-01-04 23:31:57 +00006644
6645 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6646 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6647 }
6648
6649 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6650 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6651
6652 // If the source is floating point...
6653 if (SourceBT && SourceBT->isFloatingPoint()) {
6654 // ...and the target is floating point...
6655 if (TargetBT && TargetBT->isFloatingPoint()) {
6656 // ...then warn if we're dropping FP rank.
6657
6658 // Builtin FP kinds are ordered by increasing FP rank.
6659 if (SourceBT->getKind() > TargetBT->getKind()) {
6660 // Don't warn about float constants that are precisely
6661 // representable in the target type.
6662 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00006663 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00006664 // Value might be a float, a float vector, or a float complex.
6665 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00006666 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6667 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00006668 return;
6669 }
6670
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006671 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006672 return;
6673
John McCallb4eb64d2010-10-08 02:01:28 +00006674 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00006675 }
6676 return;
6677 }
6678
Ted Kremenekef9ff882011-03-10 20:03:42 +00006679 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00006680 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006681 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006682 return;
6683
Chandler Carrutha5b93322011-02-17 11:05:49 +00006684 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00006685 // We also want to warn on, e.g., "int i = -1.234"
6686 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6687 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6688 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6689
Chandler Carruthf65076e2011-04-10 08:36:24 +00006690 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6691 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00006692 } else {
6693 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6694 }
6695 }
John McCall51313c32010-01-04 23:31:57 +00006696
Hans Wennborg88617a22012-08-28 15:44:30 +00006697 // If the target is bool, warn if expr is a function or method call.
6698 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6699 isa<CallExpr>(E)) {
6700 // Check last argument of function call to see if it is an
6701 // implicit cast from a type matching the type the result
6702 // is being cast to.
6703 CallExpr *CEx = cast<CallExpr>(E);
6704 unsigned NumArgs = CEx->getNumArgs();
6705 if (NumArgs > 0) {
6706 Expr *LastA = CEx->getArg(NumArgs - 1);
6707 Expr *InnerE = LastA->IgnoreParenImpCasts();
6708 const Type *InnerType =
6709 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6710 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6711 // Warn on this floating-point to bool conversion
6712 DiagnoseImpCast(S, E, T, CC,
6713 diag::warn_impcast_floating_point_to_bool);
6714 }
6715 }
6716 }
John McCall51313c32010-01-04 23:31:57 +00006717 return;
6718 }
6719
Stephen Hines176edba2014-12-01 14:53:08 -08006720 DiagnoseNullConversion(S, E, T, CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00006721
David Blaikieb26331b2012-06-19 21:19:06 +00006722 if (!Source->isIntegerType() || !Target->isIntegerType())
6723 return;
6724
David Blaikiebe0ee872012-05-15 16:56:36 +00006725 // TODO: remove this early return once the false positives for constant->bool
6726 // in templates, macros, etc, are reduced or removed.
6727 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6728 return;
6729
John McCall323ed742010-05-06 08:58:33 +00006730 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00006731 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00006732
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006733 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00006734 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006735 // TODO: this should happen for bitfield stores, too.
6736 llvm::APSInt Value(32);
6737 if (E->isIntegerConstantExpr(Value, S.Context)) {
6738 if (S.SourceMgr.isInSystemMacro(CC))
6739 return;
6740
John McCall091f23f2010-11-09 22:22:12 +00006741 std::string PrettySourceValue = Value.toString(10);
6742 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006743
Ted Kremenek5e745da2011-10-22 02:37:33 +00006744 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6745 S.PDiag(diag::warn_impcast_integer_precision_constant)
6746 << PrettySourceValue << PrettyTargetValue
6747 << E->getType() << T << E->getSourceRange()
6748 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00006749 return;
6750 }
6751
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006752 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6753 if (S.SourceMgr.isInSystemMacro(CC))
6754 return;
6755
David Blaikie37050842012-04-12 22:40:54 +00006756 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00006757 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6758 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00006759 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00006760 }
6761
6762 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6763 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6764 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006765
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006766 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006767 return;
6768
John McCall323ed742010-05-06 08:58:33 +00006769 unsigned DiagID = diag::warn_impcast_integer_sign;
6770
6771 // Traditionally, gcc has warned about this under -Wsign-compare.
6772 // We also want to warn about it in -Wconversion.
6773 // So if -Wconversion is off, use a completely identical diagnostic
6774 // in the sign-compare group.
6775 // The conditional-checking code will
6776 if (ICContext) {
6777 DiagID = diag::warn_impcast_integer_sign_conditional;
6778 *ICContext = true;
6779 }
6780
John McCallb4eb64d2010-10-08 02:01:28 +00006781 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00006782 }
6783
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006784 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006785 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6786 // type, to give us better diagnostics.
6787 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00006788 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006789 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6790 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6791 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6792 SourceType = S.Context.getTypeDeclType(Enum);
6793 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6794 }
6795 }
6796
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006797 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6798 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00006799 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6800 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00006801 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006802 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006803 return;
6804
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006805 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006806 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006807 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006808
John McCall51313c32010-01-04 23:31:57 +00006809 return;
6810}
6811
David Blaikie9fb1ac52012-05-15 21:57:38 +00006812void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6813 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00006814
6815void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00006816 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00006817 E = E->IgnoreParenImpCasts();
6818
6819 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00006820 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00006821
John McCallb4eb64d2010-10-08 02:01:28 +00006822 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006823 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006824 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00006825 return;
6826}
6827
David Blaikie9fb1ac52012-05-15 21:57:38 +00006828void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6829 SourceLocation CC, QualType T) {
Stephen Hines176edba2014-12-01 14:53:08 -08006830 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCall323ed742010-05-06 08:58:33 +00006831
6832 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00006833 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6834 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006835
6836 // If -Wconversion would have warned about either of the candidates
6837 // for a signedness conversion to the context type...
6838 if (!Suspicious) return;
6839
6840 // ...but it's currently ignored...
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006841 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00006842 return;
6843
John McCall323ed742010-05-06 08:58:33 +00006844 // ...then check whether it would have warned about either of the
6845 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006846 if (E->getType() == T) return;
6847
6848 Suspicious = false;
6849 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6850 E->getType(), CC, &Suspicious);
6851 if (!Suspicious)
6852 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006853 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006854}
6855
Stephen Hines176edba2014-12-01 14:53:08 -08006856/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6857/// Input argument E is a logical expression.
6858static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6859 if (S.getLangOpts().Bool)
6860 return;
6861 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6862}
6863
John McCall323ed742010-05-06 08:58:33 +00006864/// AnalyzeImplicitConversions - Find and report any interesting
6865/// implicit conversions in the given expression. There are a couple
6866/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006867void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006868 QualType T = OrigE->getType();
6869 Expr *E = OrigE->IgnoreParenImpCasts();
6870
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006871 if (E->isTypeDependent() || E->isValueDependent())
6872 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006873
John McCall323ed742010-05-06 08:58:33 +00006874 // For conditional operators, we analyze the arguments as if they
6875 // were being fed directly into the output.
6876 if (isa<ConditionalOperator>(E)) {
6877 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006878 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006879 return;
6880 }
6881
Hans Wennborg88617a22012-08-28 15:44:30 +00006882 // Check implicit argument conversions for function calls.
6883 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6884 CheckImplicitArgumentConversions(S, Call, CC);
6885
John McCall323ed742010-05-06 08:58:33 +00006886 // Go ahead and check any implicit conversions we might have skipped.
6887 // The non-canonical typecheck is just an optimization;
6888 // CheckImplicitConversion will filter out dead implicit conversions.
6889 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006890 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006891
6892 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006893
6894 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006895 if (POE->getResultExpr())
6896 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006897 }
6898
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006899 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6900 if (OVE->getSourceExpr())
6901 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6902 return;
6903 }
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006904
John McCall323ed742010-05-06 08:58:33 +00006905 // Skip past explicit casts.
6906 if (isa<ExplicitCastExpr>(E)) {
6907 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006908 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006909 }
6910
John McCallbeb22aa2010-11-09 23:24:47 +00006911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6912 // Do a somewhat different check with comparison operators.
6913 if (BO->isComparisonOp())
6914 return AnalyzeComparison(S, BO);
6915
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006916 // And with simple assignments.
6917 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006918 return AnalyzeAssignment(S, BO);
6919 }
John McCall323ed742010-05-06 08:58:33 +00006920
6921 // These break the otherwise-useful invariant below. Fortunately,
6922 // we don't really need to recurse into them, because any internal
6923 // expressions should have been analyzed already when they were
6924 // built into statements.
6925 if (isa<StmtExpr>(E)) return;
6926
6927 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006928 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006929
6930 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006931 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006932 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006933 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006934 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006935 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006936 if (!ChildExpr)
6937 continue;
6938
Stephen Hines651f13c2014-04-23 16:59:28 -07006939 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006940 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006941 // Ignore checking string literals that are in logical and operators.
6942 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006943 continue;
6944 AnalyzeImplicitConversions(S, ChildExpr, CC);
6945 }
Stephen Hines176edba2014-12-01 14:53:08 -08006946
6947 if (BO && BO->isLogicalOp()) {
6948 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6949 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006950 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006951
6952 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6953 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006954 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006955 }
6956
6957 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6958 if (U->getOpcode() == UO_LNot)
6959 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCall323ed742010-05-06 08:58:33 +00006960}
6961
6962} // end anonymous namespace
6963
Stephen Hines651f13c2014-04-23 16:59:28 -07006964enum {
6965 AddressOf,
6966 FunctionPointer,
6967 ArrayPointer
6968};
6969
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006970// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6971// Returns true when emitting a warning about taking the address of a reference.
6972static bool CheckForReference(Sema &SemaRef, const Expr *E,
6973 PartialDiagnostic PD) {
6974 E = E->IgnoreParenImpCasts();
6975
6976 const FunctionDecl *FD = nullptr;
6977
6978 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6979 if (!DRE->getDecl()->getType()->isReferenceType())
6980 return false;
6981 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6982 if (!M->getMemberDecl()->getType()->isReferenceType())
6983 return false;
6984 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006985 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006986 return false;
6987 FD = Call->getDirectCallee();
6988 } else {
6989 return false;
6990 }
6991
6992 SemaRef.Diag(E->getExprLoc(), PD);
6993
6994 // If possible, point to location of function.
6995 if (FD) {
6996 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6997 }
6998
6999 return true;
7000}
7001
Stephen Hines176edba2014-12-01 14:53:08 -08007002// Returns true if the SourceLocation is expanded from any macro body.
7003// Returns false if the SourceLocation is invalid, is from not in a macro
7004// expansion, or is from expanded from a top-level macro argument.
7005static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7006 if (Loc.isInvalid())
7007 return false;
7008
7009 while (Loc.isMacroID()) {
7010 if (SM.isMacroBodyExpansion(Loc))
7011 return true;
7012 Loc = SM.getImmediateMacroCallerLoc(Loc);
7013 }
7014
7015 return false;
7016}
7017
Stephen Hines651f13c2014-04-23 16:59:28 -07007018/// \brief Diagnose pointers that are always non-null.
7019/// \param E the expression containing the pointer
7020/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7021/// compared to a null pointer
7022/// \param IsEqual True when the comparison is equal to a null pointer
7023/// \param Range Extra SourceRange to highlight in the diagnostic
7024void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7025 Expr::NullPointerConstantKind NullKind,
7026 bool IsEqual, SourceRange Range) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007027 if (!E)
7028 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07007029
7030 // Don't warn inside macros.
Stephen Hines176edba2014-12-01 14:53:08 -08007031 if (E->getExprLoc().isMacroID()) {
7032 const SourceManager &SM = getSourceManager();
7033 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7034 IsInAnyMacroBody(SM, Range.getBegin()))
Stephen Hines651f13c2014-04-23 16:59:28 -07007035 return;
Stephen Hines176edba2014-12-01 14:53:08 -08007036 }
Stephen Hines651f13c2014-04-23 16:59:28 -07007037 E = E->IgnoreImpCasts();
7038
7039 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7040
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007041 if (isa<CXXThisExpr>(E)) {
7042 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7043 : diag::warn_this_bool_conversion;
7044 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7045 return;
7046 }
7047
Stephen Hines651f13c2014-04-23 16:59:28 -07007048 bool IsAddressOf = false;
7049
7050 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7051 if (UO->getOpcode() != UO_AddrOf)
7052 return;
7053 IsAddressOf = true;
7054 E = UO->getSubExpr();
7055 }
7056
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007057 if (IsAddressOf) {
7058 unsigned DiagID = IsCompare
7059 ? diag::warn_address_of_reference_null_compare
7060 : diag::warn_address_of_reference_bool_conversion;
7061 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7062 << IsEqual;
7063 if (CheckForReference(*this, E, PD)) {
7064 return;
7065 }
7066 }
7067
Stephen Hines651f13c2014-04-23 16:59:28 -07007068 // Expect to find a single Decl. Skip anything more complicated.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007069 ValueDecl *D = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07007070 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7071 D = R->getDecl();
7072 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7073 D = M->getMemberDecl();
7074 }
7075
7076 // Weak Decls can be null.
7077 if (!D || D->isWeak())
7078 return;
Stephen Hines176edba2014-12-01 14:53:08 -08007079
7080 // Check for parameter decl with nonnull attribute
7081 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7082 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7083 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7084 unsigned NumArgs = FD->getNumParams();
7085 llvm::SmallBitVector AttrNonNull(NumArgs);
7086 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7087 if (!NonNull->args_size()) {
7088 AttrNonNull.set(0, NumArgs);
7089 break;
7090 }
7091 for (unsigned Val : NonNull->args()) {
7092 if (Val >= NumArgs)
7093 continue;
7094 AttrNonNull.set(Val);
7095 }
7096 }
7097 if (!AttrNonNull.empty())
7098 for (unsigned i = 0; i < NumArgs; ++i)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007099 if (FD->getParamDecl(i) == PV &&
7100 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Stephen Hines176edba2014-12-01 14:53:08 -08007101 std::string Str;
7102 llvm::raw_string_ostream S(Str);
7103 E->printPretty(S, nullptr, getPrintingPolicy());
7104 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7105 : diag::warn_cast_nonnull_to_bool;
7106 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7107 << Range << IsEqual;
7108 return;
7109 }
7110 }
7111 }
7112
Stephen Hines651f13c2014-04-23 16:59:28 -07007113 QualType T = D->getType();
7114 const bool IsArray = T->isArrayType();
7115 const bool IsFunction = T->isFunctionType();
7116
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007117 // Address of function is used to silence the function warning.
7118 if (IsAddressOf && IsFunction) {
7119 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07007120 }
7121
7122 // Found nothing.
7123 if (!IsAddressOf && !IsFunction && !IsArray)
7124 return;
7125
7126 // Pretty print the expression for the diagnostic.
7127 std::string Str;
7128 llvm::raw_string_ostream S(Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007129 E->printPretty(S, nullptr, getPrintingPolicy());
Stephen Hines651f13c2014-04-23 16:59:28 -07007130
7131 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7132 : diag::warn_impcast_pointer_to_bool;
7133 unsigned DiagType;
7134 if (IsAddressOf)
7135 DiagType = AddressOf;
7136 else if (IsFunction)
7137 DiagType = FunctionPointer;
7138 else if (IsArray)
7139 DiagType = ArrayPointer;
7140 else
7141 llvm_unreachable("Could not determine diagnostic.");
7142 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7143 << Range << IsEqual;
7144
7145 if (!IsFunction)
7146 return;
7147
7148 // Suggest '&' to silence the function warning.
7149 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7150 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7151
7152 // Check to see if '()' fixit should be emitted.
7153 QualType ReturnType;
7154 UnresolvedSet<4> NonTemplateOverloads;
7155 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7156 if (ReturnType.isNull())
7157 return;
7158
7159 if (IsCompare) {
7160 // There are two cases here. If there is null constant, the only suggest
7161 // for a pointer return type. If the null is 0, then suggest if the return
7162 // type is a pointer or an integer type.
7163 if (!ReturnType->isPointerType()) {
7164 if (NullKind == Expr::NPCK_ZeroExpression ||
7165 NullKind == Expr::NPCK_ZeroLiteral) {
7166 if (!ReturnType->isIntegerType())
7167 return;
7168 } else {
7169 return;
7170 }
7171 }
7172 } else { // !IsCompare
7173 // For function to bool, only suggest if the function pointer has bool
7174 // return type.
7175 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7176 return;
7177 }
7178 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007179 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Stephen Hines651f13c2014-04-23 16:59:28 -07007180}
7181
7182
John McCall323ed742010-05-06 08:58:33 +00007183/// Diagnoses "dangerous" implicit conversions within the given
7184/// expression (which is a full expression). Implements -Wconversion
7185/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00007186///
7187/// \param CC the "context" location of the implicit conversion, i.e.
7188/// the most location of the syntactic entity requiring the implicit
7189/// conversion
7190void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00007191 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00007192 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00007193 return;
7194
7195 // Don't diagnose for value- or type-dependent expressions.
7196 if (E->isTypeDependent() || E->isValueDependent())
7197 return;
7198
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007199 // Check for array bounds violations in cases where the check isn't triggered
7200 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7201 // ArraySubscriptExpr is on the RHS of a variable initialization.
7202 CheckArrayAccess(E);
7203
John McCallb4eb64d2010-10-08 02:01:28 +00007204 // This is not the right CC for (e.g.) a variable initialization.
7205 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00007206}
7207
Stephen Hines176edba2014-12-01 14:53:08 -08007208/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7209/// Input argument E is a logical expression.
7210void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7211 ::CheckBoolLikeConversion(*this, E, CC);
7212}
7213
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007214/// Diagnose when expression is an integer constant expression and its evaluation
7215/// results in integer overflow
7216void Sema::CheckForIntOverflow (Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08007217 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7218 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007219}
7220
Richard Smith6c3af3d2013-01-17 01:17:56 +00007221namespace {
7222/// \brief Visitor for expressions which looks for unsequenced operations on the
7223/// same object.
7224class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00007225 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7226
Richard Smith6c3af3d2013-01-17 01:17:56 +00007227 /// \brief A tree of sequenced regions within an expression. Two regions are
7228 /// unsequenced if one is an ancestor or a descendent of the other. When we
7229 /// finish processing an expression with sequencing, such as a comma
7230 /// expression, we fold its tree nodes into its parent, since they are
7231 /// unsequenced with respect to nodes we will visit later.
7232 class SequenceTree {
7233 struct Value {
7234 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7235 unsigned Parent : 31;
7236 bool Merged : 1;
7237 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00007238 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007239
7240 public:
7241 /// \brief A region within an expression which may be sequenced with respect
7242 /// to some other region.
7243 class Seq {
7244 explicit Seq(unsigned N) : Index(N) {}
7245 unsigned Index;
7246 friend class SequenceTree;
7247 public:
7248 Seq() : Index(0) {}
7249 };
7250
7251 SequenceTree() { Values.push_back(Value(0)); }
7252 Seq root() const { return Seq(0); }
7253
7254 /// \brief Create a new sequence of operations, which is an unsequenced
7255 /// subset of \p Parent. This sequence of operations is sequenced with
7256 /// respect to other children of \p Parent.
7257 Seq allocate(Seq Parent) {
7258 Values.push_back(Value(Parent.Index));
7259 return Seq(Values.size() - 1);
7260 }
7261
7262 /// \brief Merge a sequence of operations into its parent.
7263 void merge(Seq S) {
7264 Values[S.Index].Merged = true;
7265 }
7266
7267 /// \brief Determine whether two operations are unsequenced. This operation
7268 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7269 /// should have been merged into its parent as appropriate.
7270 bool isUnsequenced(Seq Cur, Seq Old) {
7271 unsigned C = representative(Cur.Index);
7272 unsigned Target = representative(Old.Index);
7273 while (C >= Target) {
7274 if (C == Target)
7275 return true;
7276 C = Values[C].Parent;
7277 }
7278 return false;
7279 }
7280
7281 private:
7282 /// \brief Pick a representative for a sequence.
7283 unsigned representative(unsigned K) {
7284 if (Values[K].Merged)
7285 // Perform path compression as we go.
7286 return Values[K].Parent = representative(Values[K].Parent);
7287 return K;
7288 }
7289 };
7290
7291 /// An object for which we can track unsequenced uses.
7292 typedef NamedDecl *Object;
7293
7294 /// Different flavors of object usage which we track. We only track the
7295 /// least-sequenced usage of each kind.
7296 enum UsageKind {
7297 /// A read of an object. Multiple unsequenced reads are OK.
7298 UK_Use,
7299 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00007300 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00007301 UK_ModAsValue,
7302 /// A modification of an object which is not sequenced before the value
7303 /// computation of the expression, such as n++.
7304 UK_ModAsSideEffect,
7305
7306 UK_Count = UK_ModAsSideEffect + 1
7307 };
7308
7309 struct Usage {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007310 Usage() : Use(nullptr), Seq() {}
Richard Smith6c3af3d2013-01-17 01:17:56 +00007311 Expr *Use;
7312 SequenceTree::Seq Seq;
7313 };
7314
7315 struct UsageInfo {
7316 UsageInfo() : Diagnosed(false) {}
7317 Usage Uses[UK_Count];
7318 /// Have we issued a diagnostic for this variable already?
7319 bool Diagnosed;
7320 };
7321 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7322
7323 Sema &SemaRef;
7324 /// Sequenced regions within the expression.
7325 SequenceTree Tree;
7326 /// Declaration modifications and references which we have seen.
7327 UsageInfoMap UsageMap;
7328 /// The region we are currently within.
7329 SequenceTree::Seq Region;
7330 /// Filled in with declarations which were modified as a side-effect
7331 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00007332 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007333 /// Expressions to check later. We defer checking these to reduce
7334 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007335 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007336
7337 /// RAII object wrapping the visitation of a sequenced subexpression of an
7338 /// expression. At the end of this process, the side-effects of the evaluation
7339 /// become sequenced with respect to the value computation of the result, so
7340 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7341 /// UK_ModAsValue.
7342 struct SequencedSubexpression {
7343 SequencedSubexpression(SequenceChecker &Self)
7344 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7345 Self.ModAsSideEffect = &ModAsSideEffect;
7346 }
7347 ~SequencedSubexpression() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007348 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7349 MI != ME; ++MI) {
7350 UsageInfo &U = Self.UsageMap[MI->first];
7351 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7352 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7353 SideEffectUsage = MI->second;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007354 }
7355 Self.ModAsSideEffect = OldModAsSideEffect;
7356 }
7357
7358 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00007359 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7360 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007361 };
7362
Richard Smith67470052013-06-20 22:21:56 +00007363 /// RAII object wrapping the visitation of a subexpression which we might
7364 /// choose to evaluate as a constant. If any subexpression is evaluated and
7365 /// found to be non-constant, this allows us to suppress the evaluation of
7366 /// the outer expression.
7367 class EvaluationTracker {
7368 public:
7369 EvaluationTracker(SequenceChecker &Self)
7370 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7371 Self.EvalTracker = this;
7372 }
7373 ~EvaluationTracker() {
7374 Self.EvalTracker = Prev;
7375 if (Prev)
7376 Prev->EvalOK &= EvalOK;
7377 }
7378
7379 bool evaluate(const Expr *E, bool &Result) {
7380 if (!EvalOK || E->isValueDependent())
7381 return false;
7382 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7383 return EvalOK;
7384 }
7385
7386 private:
7387 SequenceChecker &Self;
7388 EvaluationTracker *Prev;
7389 bool EvalOK;
7390 } *EvalTracker;
7391
Richard Smith6c3af3d2013-01-17 01:17:56 +00007392 /// \brief Find the object which is produced by the specified expression,
7393 /// if any.
7394 Object getObject(Expr *E, bool Mod) const {
7395 E = E->IgnoreParenCasts();
7396 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7397 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7398 return getObject(UO->getSubExpr(), Mod);
7399 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7400 if (BO->getOpcode() == BO_Comma)
7401 return getObject(BO->getRHS(), Mod);
7402 if (Mod && BO->isAssignmentOp())
7403 return getObject(BO->getLHS(), Mod);
7404 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7405 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7406 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7407 return ME->getMemberDecl();
7408 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7409 // FIXME: If this is a reference, map through to its value.
7410 return DRE->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007411 return nullptr;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007412 }
7413
7414 /// \brief Note that an object was modified or used by an expression.
7415 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7416 Usage &U = UI.Uses[UK];
7417 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7418 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7419 ModAsSideEffect->push_back(std::make_pair(O, U));
7420 U.Use = Ref;
7421 U.Seq = Region;
7422 }
7423 }
7424 /// \brief Check whether a modification or use conflicts with a prior usage.
7425 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7426 bool IsModMod) {
7427 if (UI.Diagnosed)
7428 return;
7429
7430 const Usage &U = UI.Uses[OtherKind];
7431 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7432 return;
7433
7434 Expr *Mod = U.Use;
7435 Expr *ModOrUse = Ref;
7436 if (OtherKind == UK_Use)
7437 std::swap(Mod, ModOrUse);
7438
7439 SemaRef.Diag(Mod->getExprLoc(),
7440 IsModMod ? diag::warn_unsequenced_mod_mod
7441 : diag::warn_unsequenced_mod_use)
7442 << O << SourceRange(ModOrUse->getExprLoc());
7443 UI.Diagnosed = true;
7444 }
7445
7446 void notePreUse(Object O, Expr *Use) {
7447 UsageInfo &U = UsageMap[O];
7448 // Uses conflict with other modifications.
7449 checkUsage(O, U, Use, UK_ModAsValue, false);
7450 }
7451 void notePostUse(Object O, Expr *Use) {
7452 UsageInfo &U = UsageMap[O];
7453 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7454 addUsage(U, O, Use, UK_Use);
7455 }
7456
7457 void notePreMod(Object O, Expr *Mod) {
7458 UsageInfo &U = UsageMap[O];
7459 // Modifications conflict with other modifications and with uses.
7460 checkUsage(O, U, Mod, UK_ModAsValue, true);
7461 checkUsage(O, U, Mod, UK_Use, false);
7462 }
7463 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7464 UsageInfo &U = UsageMap[O];
7465 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7466 addUsage(U, O, Use, UK);
7467 }
7468
7469public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00007470 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007471 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7472 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007473 Visit(E);
7474 }
7475
7476 void VisitStmt(Stmt *S) {
7477 // Skip all statements which aren't expressions for now.
7478 }
7479
7480 void VisitExpr(Expr *E) {
7481 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00007482 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007483 }
7484
7485 void VisitCastExpr(CastExpr *E) {
7486 Object O = Object();
7487 if (E->getCastKind() == CK_LValueToRValue)
7488 O = getObject(E->getSubExpr(), false);
7489
7490 if (O)
7491 notePreUse(O, E);
7492 VisitExpr(E);
7493 if (O)
7494 notePostUse(O, E);
7495 }
7496
7497 void VisitBinComma(BinaryOperator *BO) {
7498 // C++11 [expr.comma]p1:
7499 // Every value computation and side effect associated with the left
7500 // expression is sequenced before every value computation and side
7501 // effect associated with the right expression.
7502 SequenceTree::Seq LHS = Tree.allocate(Region);
7503 SequenceTree::Seq RHS = Tree.allocate(Region);
7504 SequenceTree::Seq OldRegion = Region;
7505
7506 {
7507 SequencedSubexpression SeqLHS(*this);
7508 Region = LHS;
7509 Visit(BO->getLHS());
7510 }
7511
7512 Region = RHS;
7513 Visit(BO->getRHS());
7514
7515 Region = OldRegion;
7516
7517 // Forget that LHS and RHS are sequenced. They are both unsequenced
7518 // with respect to other stuff.
7519 Tree.merge(LHS);
7520 Tree.merge(RHS);
7521 }
7522
7523 void VisitBinAssign(BinaryOperator *BO) {
7524 // The modification is sequenced after the value computation of the LHS
7525 // and RHS, so check it before inspecting the operands and update the
7526 // map afterwards.
7527 Object O = getObject(BO->getLHS(), true);
7528 if (!O)
7529 return VisitExpr(BO);
7530
7531 notePreMod(O, BO);
7532
7533 // C++11 [expr.ass]p7:
7534 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7535 // only once.
7536 //
7537 // Therefore, for a compound assignment operator, O is considered used
7538 // everywhere except within the evaluation of E1 itself.
7539 if (isa<CompoundAssignOperator>(BO))
7540 notePreUse(O, BO);
7541
7542 Visit(BO->getLHS());
7543
7544 if (isa<CompoundAssignOperator>(BO))
7545 notePostUse(O, BO);
7546
7547 Visit(BO->getRHS());
7548
Richard Smith418dd3e2013-06-26 23:16:51 +00007549 // C++11 [expr.ass]p1:
7550 // the assignment is sequenced [...] before the value computation of the
7551 // assignment expression.
7552 // C11 6.5.16/3 has no such rule.
7553 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7554 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007555 }
7556 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7557 VisitBinAssign(CAO);
7558 }
7559
7560 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7561 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7562 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7563 Object O = getObject(UO->getSubExpr(), true);
7564 if (!O)
7565 return VisitExpr(UO);
7566
7567 notePreMod(O, UO);
7568 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00007569 // C++11 [expr.pre.incr]p1:
7570 // the expression ++x is equivalent to x+=1
7571 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7572 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007573 }
7574
7575 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7576 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7577 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7578 Object O = getObject(UO->getSubExpr(), true);
7579 if (!O)
7580 return VisitExpr(UO);
7581
7582 notePreMod(O, UO);
7583 Visit(UO->getSubExpr());
7584 notePostMod(O, UO, UK_ModAsSideEffect);
7585 }
7586
7587 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7588 void VisitBinLOr(BinaryOperator *BO) {
7589 // The side-effects of the LHS of an '&&' are sequenced before the
7590 // value computation of the RHS, and hence before the value computation
7591 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7592 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00007593 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007594 {
7595 SequencedSubexpression Sequenced(*this);
7596 Visit(BO->getLHS());
7597 }
7598
7599 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007600 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007601 if (!Result)
7602 Visit(BO->getRHS());
7603 } else {
7604 // Check for unsequenced operations in the RHS, treating it as an
7605 // entirely separate evaluation.
7606 //
7607 // FIXME: If there are operations in the RHS which are unsequenced
7608 // with respect to operations outside the RHS, and those operations
7609 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00007610 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007611 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007612 }
7613 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00007614 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007615 {
7616 SequencedSubexpression Sequenced(*this);
7617 Visit(BO->getLHS());
7618 }
7619
7620 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007621 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007622 if (Result)
7623 Visit(BO->getRHS());
7624 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007625 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007626 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007627 }
7628
7629 // Only visit the condition, unless we can be sure which subexpression will
7630 // be chosen.
7631 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00007632 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00007633 {
7634 SequencedSubexpression Sequenced(*this);
7635 Visit(CO->getCond());
7636 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007637
7638 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007639 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00007640 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007641 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007642 WorkList.push_back(CO->getTrueExpr());
7643 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007644 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007645 }
7646
Richard Smith0c0b3902013-06-30 10:40:20 +00007647 void VisitCallExpr(CallExpr *CE) {
7648 // C++11 [intro.execution]p15:
7649 // When calling a function [...], every value computation and side effect
7650 // associated with any argument expression, or with the postfix expression
7651 // designating the called function, is sequenced before execution of every
7652 // expression or statement in the body of the function [and thus before
7653 // the value computation of its result].
7654 SequencedSubexpression Sequenced(*this);
7655 Base::VisitCallExpr(CE);
7656
7657 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7658 }
7659
Richard Smith6c3af3d2013-01-17 01:17:56 +00007660 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00007661 // This is a call, so all subexpressions are sequenced before the result.
7662 SequencedSubexpression Sequenced(*this);
7663
Richard Smith6c3af3d2013-01-17 01:17:56 +00007664 if (!CCE->isListInitialization())
7665 return VisitExpr(CCE);
7666
7667 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007668 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007669 SequenceTree::Seq Parent = Region;
7670 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7671 E = CCE->arg_end();
7672 I != E; ++I) {
7673 Region = Tree.allocate(Parent);
7674 Elts.push_back(Region);
7675 Visit(*I);
7676 }
7677
7678 // Forget that the initializers are sequenced.
7679 Region = Parent;
7680 for (unsigned I = 0; I < Elts.size(); ++I)
7681 Tree.merge(Elts[I]);
7682 }
7683
7684 void VisitInitListExpr(InitListExpr *ILE) {
7685 if (!SemaRef.getLangOpts().CPlusPlus11)
7686 return VisitExpr(ILE);
7687
7688 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007689 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007690 SequenceTree::Seq Parent = Region;
7691 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7692 Expr *E = ILE->getInit(I);
7693 if (!E) continue;
7694 Region = Tree.allocate(Parent);
7695 Elts.push_back(Region);
7696 Visit(E);
7697 }
7698
7699 // Forget that the initializers are sequenced.
7700 Region = Parent;
7701 for (unsigned I = 0; I < Elts.size(); ++I)
7702 Tree.merge(Elts[I]);
7703 }
7704};
7705}
7706
7707void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00007708 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007709 WorkList.push_back(E);
7710 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00007711 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00007712 SequenceChecker(*this, Item, WorkList);
7713 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007714}
7715
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007716void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7717 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007718 CheckImplicitConversions(E, CheckLoc);
7719 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007720 if (!IsConstexpr && !E->isValueDependent())
7721 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007722}
7723
John McCall15d7d122010-11-11 03:21:53 +00007724void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7725 FieldDecl *BitField,
7726 Expr *Init) {
7727 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7728}
7729
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07007730static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7731 SourceLocation Loc) {
7732 if (!PType->isVariablyModifiedType())
7733 return;
7734 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7735 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7736 return;
7737 }
7738 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7739 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7740 return;
7741 }
7742 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7743 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7744 return;
7745 }
7746
7747 const ArrayType *AT = S.Context.getAsArrayType(PType);
7748 if (!AT)
7749 return;
7750
7751 if (AT->getSizeModifier() != ArrayType::Star) {
7752 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7753 return;
7754 }
7755
7756 S.Diag(Loc, diag::err_array_star_in_function_definition);
7757}
7758
Mike Stumpf8c49212010-01-21 03:59:47 +00007759/// CheckParmsForFunctionDef - Check that the parameters of the given
7760/// function are appropriate for the definition of a function. This
7761/// takes care of any checks that cannot be performed on the
7762/// declaration itself, e.g., that the types of each of the function
7763/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00007764bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7765 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00007766 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007767 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00007768 for (; P != PEnd; ++P) {
7769 ParmVarDecl *Param = *P;
7770
Mike Stumpf8c49212010-01-21 03:59:47 +00007771 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7772 // function declarator that is part of a function definition of
7773 // that function shall not have incomplete type.
7774 //
7775 // This is also C++ [dcl.fct]p6.
7776 if (!Param->isInvalidDecl() &&
7777 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007778 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007779 Param->setInvalidDecl();
7780 HasInvalidParm = true;
7781 }
7782
7783 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7784 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00007785 if (CheckParameterNames &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007786 Param->getIdentifier() == nullptr &&
Mike Stumpf8c49212010-01-21 03:59:47 +00007787 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007788 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00007789 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00007790
7791 // C99 6.7.5.3p12:
7792 // If the function declarator is not part of a definition of that
7793 // function, parameters may have incomplete type and may use the [*]
7794 // notation in their sequences of declarator specifiers to specify
7795 // variable length array types.
7796 QualType PType = Param->getOriginalType();
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07007797 // FIXME: This diagnostic should point the '[*]' if source-location
7798 // information is added for it.
7799 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner9b601952013-06-21 12:45:15 +00007800
7801 // MSVC destroys objects passed by value in the callee. Therefore a
7802 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07007803 // object's destructor. However, we don't perform any direct access check
7804 // on the dtor.
7805 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7806 .getCXXABI()
7807 .areArgsDestroyedLeftToRightInCallee()) {
7808 if (!Param->isInvalidDecl()) {
7809 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7810 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7811 if (!ClassDecl->isInvalidDecl() &&
7812 !ClassDecl->hasIrrelevantDestructor() &&
7813 !ClassDecl->isDependentContext()) {
7814 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7815 MarkFunctionReferenced(Param->getLocation(), Destructor);
7816 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7817 }
7818 }
7819 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007820 }
Mike Stumpf8c49212010-01-21 03:59:47 +00007821 }
7822
7823 return HasInvalidParm;
7824}
John McCallb7f4ffe2010-08-12 21:44:57 +00007825
7826/// CheckCastAlign - Implements -Wcast-align, which warns when a
7827/// pointer cast increases the alignment requirements.
7828void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7829 // This is actually a lot of work to potentially be doing on every
7830 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007831 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCallb7f4ffe2010-08-12 21:44:57 +00007832 return;
7833
7834 // Ignore dependent types.
7835 if (T->isDependentType() || Op->getType()->isDependentType())
7836 return;
7837
7838 // Require that the destination be a pointer type.
7839 const PointerType *DestPtr = T->getAs<PointerType>();
7840 if (!DestPtr) return;
7841
7842 // If the destination has alignment 1, we're done.
7843 QualType DestPointee = DestPtr->getPointeeType();
7844 if (DestPointee->isIncompleteType()) return;
7845 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7846 if (DestAlign.isOne()) return;
7847
7848 // Require that the source be a pointer type.
7849 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7850 if (!SrcPtr) return;
7851 QualType SrcPointee = SrcPtr->getPointeeType();
7852
7853 // Whitelist casts from cv void*. We already implicitly
7854 // whitelisted casts to cv void*, since they have alignment 1.
7855 // Also whitelist casts involving incomplete types, which implicitly
7856 // includes 'void'.
7857 if (SrcPointee->isIncompleteType()) return;
7858
7859 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7860 if (SrcAlign >= DestAlign) return;
7861
7862 Diag(TRange.getBegin(), diag::warn_cast_align)
7863 << Op->getType() << T
7864 << static_cast<unsigned>(SrcAlign.getQuantity())
7865 << static_cast<unsigned>(DestAlign.getQuantity())
7866 << TRange << Op->getSourceRange();
7867}
7868
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007869static const Type* getElementType(const Expr *BaseExpr) {
7870 const Type* EltType = BaseExpr->getType().getTypePtr();
7871 if (EltType->isAnyPointerType())
7872 return EltType->getPointeeType().getTypePtr();
7873 else if (EltType->isArrayType())
7874 return EltType->getBaseElementTypeUnsafe();
7875 return EltType;
7876}
7877
Chandler Carruthc2684342011-08-05 09:10:50 +00007878/// \brief Check whether this array fits the idiom of a size-one tail padded
7879/// array member of a struct.
7880///
7881/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7882/// commonly used to emulate flexible arrays in C89 code.
7883static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7884 const NamedDecl *ND) {
7885 if (Size != 1 || !ND) return false;
7886
7887 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7888 if (!FD) return false;
7889
7890 // Don't consider sizes resulting from macro expansions or template argument
7891 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00007892
7893 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007894 while (TInfo) {
7895 TypeLoc TL = TInfo->getTypeLoc();
7896 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00007897 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7898 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007899 TInfo = TDL->getTypeSourceInfo();
7900 continue;
7901 }
David Blaikie39e6ab42013-02-18 22:06:02 +00007902 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7903 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00007904 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7905 return false;
7906 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007907 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00007908 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007909
7910 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00007911 if (!RD) return false;
7912 if (RD->isUnion()) return false;
7913 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7914 if (!CRD->isStandardLayout()) return false;
7915 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007916
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00007917 // See if this is the last field decl in the record.
7918 const Decl *D = FD;
7919 while ((D = D->getNextDeclInContext()))
7920 if (isa<FieldDecl>(D))
7921 return false;
7922 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00007923}
7924
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007925void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007926 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00007927 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00007928 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007929 if (IndexExpr->isValueDependent())
7930 return;
7931
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00007932 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007933 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00007934 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007935 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00007936 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00007937 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00007938
Chandler Carruth34064582011-02-17 20:55:08 +00007939 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007940 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00007941 return;
Richard Smith25b009a2011-12-16 19:31:14 +00007942 if (IndexNegated)
7943 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007944
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007945 const NamedDecl *ND = nullptr;
Chandler Carruthba447122011-08-05 08:07:29 +00007946 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7947 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00007948 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00007949 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00007950
Ted Kremenek9e060ca2011-02-23 23:06:04 +00007951 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00007952 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00007953 if (!size.isStrictlyPositive())
7954 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007955
7956 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00007957 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007958 // Make sure we're comparing apples to apples when comparing index to size
7959 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7960 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00007961 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00007962 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007963 if (ptrarith_typesize != array_typesize) {
7964 // There's a cast to a different size type involved
7965 uint64_t ratio = array_typesize / ptrarith_typesize;
7966 // TODO: Be smarter about handling cases where array_typesize is not a
7967 // multiple of ptrarith_typesize
7968 if (ptrarith_typesize * ratio == array_typesize)
7969 size *= llvm::APInt(size.getBitWidth(), ratio);
7970 }
7971 }
7972
Chandler Carruth34064582011-02-17 20:55:08 +00007973 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007974 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007975 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007976 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007977
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007978 // For array subscripting the index must be less than size, but for pointer
7979 // arithmetic also allow the index (offset) to be equal to size since
7980 // computing the next address after the end of the array is legal and
7981 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00007982 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00007983 return;
7984
7985 // Also don't warn for arrays of size 1 which are members of some
7986 // structure. These are often used to approximate flexible arrays in C89
7987 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007988 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007989 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007990
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007991 // Suppress the warning if the subscript expression (as identified by the
7992 // ']' location) and the index expression are both from macro expansions
7993 // within a system header.
7994 if (ASE) {
7995 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7996 ASE->getRBracketLoc());
7997 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7998 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7999 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00008000 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00008001 return;
8002 }
8003 }
8004
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008005 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00008006 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008007 DiagID = diag::warn_array_index_exceeds_bounds;
8008
8009 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8010 PDiag(DiagID) << index.toString(10, true)
8011 << size.toString(10, true)
8012 << (unsigned)size.getLimitedValue(~0U)
8013 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00008014 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008015 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00008016 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008017 DiagID = diag::warn_ptr_arith_precedes_bounds;
8018 if (index.isNegative()) index = -index;
8019 }
8020
8021 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8022 PDiag(DiagID) << index.toString(10, true)
8023 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008024 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00008025
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00008026 if (!ND) {
8027 // Try harder to find a NamedDecl to point at in the note.
8028 while (const ArraySubscriptExpr *ASE =
8029 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8030 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8031 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8032 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8033 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8034 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8035 }
8036
Chandler Carruth35001ca2011-02-17 21:10:52 +00008037 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008038 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8039 PDiag(diag::note_array_index_out_of_bounds)
8040 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008041}
8042
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008043void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008044 int AllowOnePastEnd = 0;
8045 while (expr) {
8046 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008047 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008048 case Stmt::ArraySubscriptExprClass: {
8049 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00008050 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008051 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008052 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00008053 }
8054 case Stmt::UnaryOperatorClass: {
8055 // Only unwrap the * and & unary operators
8056 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8057 expr = UO->getSubExpr();
8058 switch (UO->getOpcode()) {
8059 case UO_AddrOf:
8060 AllowOnePastEnd++;
8061 break;
8062 case UO_Deref:
8063 AllowOnePastEnd--;
8064 break;
8065 default:
8066 return;
8067 }
8068 break;
8069 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008070 case Stmt::ConditionalOperatorClass: {
8071 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8072 if (const Expr *lhs = cond->getLHS())
8073 CheckArrayAccess(lhs);
8074 if (const Expr *rhs = cond->getRHS())
8075 CheckArrayAccess(rhs);
8076 return;
8077 }
8078 default:
8079 return;
8080 }
Peter Collingbournef111d932011-04-15 00:35:48 +00008081 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008082}
John McCallf85e1932011-06-15 23:02:42 +00008083
8084//===--- CHECK: Objective-C retain cycles ----------------------------------//
8085
8086namespace {
8087 struct RetainCycleOwner {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008088 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCallf85e1932011-06-15 23:02:42 +00008089 VarDecl *Variable;
8090 SourceRange Range;
8091 SourceLocation Loc;
8092 bool Indirect;
8093
8094 void setLocsFrom(Expr *e) {
8095 Loc = e->getExprLoc();
8096 Range = e->getSourceRange();
8097 }
8098 };
8099}
8100
8101/// Consider whether capturing the given variable can possibly lead to
8102/// a retain cycle.
8103static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00008104 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00008105 // lifetime. In MRR, it's captured strongly if the variable is
8106 // __block and has an appropriate type.
8107 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8108 return false;
8109
8110 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00008111 if (ref)
8112 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00008113 return true;
8114}
8115
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008116static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00008117 while (true) {
8118 e = e->IgnoreParens();
8119 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8120 switch (cast->getCastKind()) {
8121 case CK_BitCast:
8122 case CK_LValueBitCast:
8123 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00008124 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00008125 e = cast->getSubExpr();
8126 continue;
8127
John McCallf85e1932011-06-15 23:02:42 +00008128 default:
8129 return false;
8130 }
8131 }
8132
8133 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8134 ObjCIvarDecl *ivar = ref->getDecl();
8135 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8136 return false;
8137
8138 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008139 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00008140 return false;
8141
8142 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8143 owner.Indirect = true;
8144 return true;
8145 }
8146
8147 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8148 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8149 if (!var) return false;
8150 return considerVariable(var, ref, owner);
8151 }
8152
John McCallf85e1932011-06-15 23:02:42 +00008153 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8154 if (member->isArrow()) return false;
8155
8156 // Don't count this as an indirect ownership.
8157 e = member->getBase();
8158 continue;
8159 }
8160
John McCall4b9c2d22011-11-06 09:01:30 +00008161 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8162 // Only pay attention to pseudo-objects on property references.
8163 ObjCPropertyRefExpr *pre
8164 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8165 ->IgnoreParens());
8166 if (!pre) return false;
8167 if (pre->isImplicitProperty()) return false;
8168 ObjCPropertyDecl *property = pre->getExplicitProperty();
8169 if (!property->isRetaining() &&
8170 !(property->getPropertyIvarDecl() &&
8171 property->getPropertyIvarDecl()->getType()
8172 .getObjCLifetime() == Qualifiers::OCL_Strong))
8173 return false;
8174
8175 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008176 if (pre->isSuperReceiver()) {
8177 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8178 if (!owner.Variable)
8179 return false;
8180 owner.Loc = pre->getLocation();
8181 owner.Range = pre->getSourceRange();
8182 return true;
8183 }
John McCall4b9c2d22011-11-06 09:01:30 +00008184 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8185 ->getSourceExpr());
8186 continue;
8187 }
8188
John McCallf85e1932011-06-15 23:02:42 +00008189 // Array ivars?
8190
8191 return false;
8192 }
8193}
8194
8195namespace {
8196 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8197 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8198 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008199 Context(Context), Variable(variable), Capturer(nullptr),
8200 VarWillBeReased(false) {}
8201 ASTContext &Context;
John McCallf85e1932011-06-15 23:02:42 +00008202 VarDecl *Variable;
8203 Expr *Capturer;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008204 bool VarWillBeReased;
John McCallf85e1932011-06-15 23:02:42 +00008205
8206 void VisitDeclRefExpr(DeclRefExpr *ref) {
8207 if (ref->getDecl() == Variable && !Capturer)
8208 Capturer = ref;
8209 }
8210
John McCallf85e1932011-06-15 23:02:42 +00008211 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8212 if (Capturer) return;
8213 Visit(ref->getBase());
8214 if (Capturer && ref->isFreeIvar())
8215 Capturer = ref;
8216 }
8217
8218 void VisitBlockExpr(BlockExpr *block) {
8219 // Look inside nested blocks
8220 if (block->getBlockDecl()->capturesVariable(Variable))
8221 Visit(block->getBlockDecl()->getBody());
8222 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00008223
8224 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8225 if (Capturer) return;
8226 if (OVE->getSourceExpr())
8227 Visit(OVE->getSourceExpr());
8228 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008229 void VisitBinaryOperator(BinaryOperator *BinOp) {
8230 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8231 return;
8232 Expr *LHS = BinOp->getLHS();
8233 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8234 if (DRE->getDecl() != Variable)
8235 return;
8236 if (Expr *RHS = BinOp->getRHS()) {
8237 RHS = RHS->IgnoreParenCasts();
8238 llvm::APSInt Value;
8239 VarWillBeReased =
8240 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8241 }
8242 }
8243 }
John McCallf85e1932011-06-15 23:02:42 +00008244 };
8245}
8246
8247/// Check whether the given argument is a block which captures a
8248/// variable.
8249static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8250 assert(owner.Variable && owner.Loc.isValid());
8251
8252 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00008253
8254 // Look through [^{...} copy] and Block_copy(^{...}).
8255 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8256 Selector Cmd = ME->getSelector();
8257 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8258 e = ME->getInstanceReceiver();
8259 if (!e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008260 return nullptr;
Jordan Rose1fac58a2012-09-17 17:54:30 +00008261 e = e->IgnoreParenCasts();
8262 }
8263 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8264 if (CE->getNumArgs() == 1) {
8265 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00008266 if (Fn) {
8267 const IdentifierInfo *FnI = Fn->getIdentifier();
8268 if (FnI && FnI->isStr("_Block_copy")) {
8269 e = CE->getArg(0)->IgnoreParenCasts();
8270 }
8271 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00008272 }
8273 }
8274
John McCallf85e1932011-06-15 23:02:42 +00008275 BlockExpr *block = dyn_cast<BlockExpr>(e);
8276 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008277 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00008278
8279 FindCaptureVisitor visitor(S.Context, owner.Variable);
8280 visitor.Visit(block->getBlockDecl()->getBody());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008281 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCallf85e1932011-06-15 23:02:42 +00008282}
8283
8284static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8285 RetainCycleOwner &owner) {
8286 assert(capturer);
8287 assert(owner.Variable && owner.Loc.isValid());
8288
8289 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8290 << owner.Variable << capturer->getSourceRange();
8291 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8292 << owner.Indirect << owner.Range;
8293}
8294
8295/// Check for a keyword selector that starts with the word 'add' or
8296/// 'set'.
8297static bool isSetterLikeSelector(Selector sel) {
8298 if (sel.isUnarySelector()) return false;
8299
Chris Lattner5f9e2722011-07-23 10:55:15 +00008300 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00008301 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008302 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00008303 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008304 else if (str.startswith("add")) {
8305 // Specially whitelist 'addOperationWithBlock:'.
8306 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8307 return false;
8308 str = str.substr(3);
8309 }
John McCallf85e1932011-06-15 23:02:42 +00008310 else
8311 return false;
8312
8313 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00008314 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00008315}
8316
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008317static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8318 ObjCMessageExpr *Message) {
8319 if (S.NSMutableArrayPointer.isNull()) {
8320 IdentifierInfo *NSMutableArrayId =
8321 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8322 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8323 Message->getLocStart(),
8324 Sema::LookupOrdinaryName);
8325 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8326 if (!InterfaceDecl) {
8327 return None;
8328 }
8329 QualType NSMutableArrayObject =
8330 S.Context.getObjCInterfaceType(InterfaceDecl);
8331 S.NSMutableArrayPointer =
8332 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8333 }
8334
8335 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8336 return None;
8337 }
8338
8339 Selector Sel = Message->getSelector();
8340
8341 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8342 S.NSAPIObj->getNSArrayMethodKind(Sel);
8343 if (!MKOpt) {
8344 return None;
8345 }
8346
8347 NSAPI::NSArrayMethodKind MK = *MKOpt;
8348
8349 switch (MK) {
8350 case NSAPI::NSMutableArr_addObject:
8351 case NSAPI::NSMutableArr_insertObjectAtIndex:
8352 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8353 return 0;
8354 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8355 return 1;
8356
8357 default:
8358 return None;
8359 }
8360
8361 return None;
8362}
8363
8364static
8365Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8366 ObjCMessageExpr *Message) {
8367
8368 if (S.NSMutableDictionaryPointer.isNull()) {
8369 IdentifierInfo *NSMutableDictionaryId =
8370 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8371 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8372 Message->getLocStart(),
8373 Sema::LookupOrdinaryName);
8374 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8375 if (!InterfaceDecl) {
8376 return None;
8377 }
8378 QualType NSMutableDictionaryObject =
8379 S.Context.getObjCInterfaceType(InterfaceDecl);
8380 S.NSMutableDictionaryPointer =
8381 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8382 }
8383
8384 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8385 return None;
8386 }
8387
8388 Selector Sel = Message->getSelector();
8389
8390 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8391 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8392 if (!MKOpt) {
8393 return None;
8394 }
8395
8396 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8397
8398 switch (MK) {
8399 case NSAPI::NSMutableDict_setObjectForKey:
8400 case NSAPI::NSMutableDict_setValueForKey:
8401 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8402 return 0;
8403
8404 default:
8405 return None;
8406 }
8407
8408 return None;
8409}
8410
8411static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8412
8413 ObjCInterfaceDecl *InterfaceDecl;
8414 if (S.NSMutableSetPointer.isNull()) {
8415 IdentifierInfo *NSMutableSetId =
8416 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8417 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8418 Message->getLocStart(),
8419 Sema::LookupOrdinaryName);
8420 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8421 if (InterfaceDecl) {
8422 QualType NSMutableSetObject =
8423 S.Context.getObjCInterfaceType(InterfaceDecl);
8424 S.NSMutableSetPointer =
8425 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8426 }
8427 }
8428
8429 if (S.NSCountedSetPointer.isNull()) {
8430 IdentifierInfo *NSCountedSetId =
8431 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8432 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8433 Message->getLocStart(),
8434 Sema::LookupOrdinaryName);
8435 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8436 if (InterfaceDecl) {
8437 QualType NSCountedSetObject =
8438 S.Context.getObjCInterfaceType(InterfaceDecl);
8439 S.NSCountedSetPointer =
8440 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8441 }
8442 }
8443
8444 if (S.NSMutableOrderedSetPointer.isNull()) {
8445 IdentifierInfo *NSOrderedSetId =
8446 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8447 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8448 Message->getLocStart(),
8449 Sema::LookupOrdinaryName);
8450 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8451 if (InterfaceDecl) {
8452 QualType NSOrderedSetObject =
8453 S.Context.getObjCInterfaceType(InterfaceDecl);
8454 S.NSMutableOrderedSetPointer =
8455 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8456 }
8457 }
8458
8459 QualType ReceiverType = Message->getReceiverType();
8460
8461 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8462 ReceiverType == S.NSMutableSetPointer;
8463 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8464 ReceiverType == S.NSMutableOrderedSetPointer;
8465 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8466 ReceiverType == S.NSCountedSetPointer;
8467
8468 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8469 return None;
8470 }
8471
8472 Selector Sel = Message->getSelector();
8473
8474 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8475 if (!MKOpt) {
8476 return None;
8477 }
8478
8479 NSAPI::NSSetMethodKind MK = *MKOpt;
8480
8481 switch (MK) {
8482 case NSAPI::NSMutableSet_addObject:
8483 case NSAPI::NSOrderedSet_setObjectAtIndex:
8484 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8485 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8486 return 0;
8487 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8488 return 1;
8489 }
8490
8491 return None;
8492}
8493
8494void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8495 if (!Message->isInstanceMessage()) {
8496 return;
8497 }
8498
8499 Optional<int> ArgOpt;
8500
8501 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8502 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8503 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8504 return;
8505 }
8506
8507 int ArgIndex = *ArgOpt;
8508
8509 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8510 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8511 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8512 }
8513
8514 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8515 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8516 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8517 }
8518
8519 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8520 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8521 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8522 ValueDecl *Decl = ReceiverRE->getDecl();
8523 Diag(Message->getSourceRange().getBegin(),
8524 diag::warn_objc_circular_container)
8525 << Decl->getName();
8526 Diag(Decl->getLocation(),
8527 diag::note_objc_circular_container_declared_here)
8528 << Decl->getName();
8529 }
8530 }
8531 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8532 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8533 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8534 ObjCIvarDecl *Decl = IvarRE->getDecl();
8535 Diag(Message->getSourceRange().getBegin(),
8536 diag::warn_objc_circular_container)
8537 << Decl->getName();
8538 Diag(Decl->getLocation(),
8539 diag::note_objc_circular_container_declared_here)
8540 << Decl->getName();
8541 }
8542 }
8543 }
8544
8545}
8546
John McCallf85e1932011-06-15 23:02:42 +00008547/// Check a message send to see if it's likely to cause a retain cycle.
8548void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8549 // Only check instance methods whose selector looks like a setter.
8550 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8551 return;
8552
8553 // Try to find a variable that the receiver is strongly owned by.
8554 RetainCycleOwner owner;
8555 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008556 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00008557 return;
8558 } else {
8559 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8560 owner.Variable = getCurMethodDecl()->getSelfDecl();
8561 owner.Loc = msg->getSuperLoc();
8562 owner.Range = msg->getSuperLoc();
8563 }
8564
8565 // Check whether the receiver is captured by any of the arguments.
8566 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8567 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8568 return diagnoseRetainCycle(*this, capturer, owner);
8569}
8570
8571/// Check a property assign to see if it's likely to cause a retain cycle.
8572void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8573 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008574 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00008575 return;
8576
8577 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8578 diagnoseRetainCycle(*this, capturer, owner);
8579}
8580
Jordan Rosee10f4d32012-09-15 02:48:31 +00008581void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8582 RetainCycleOwner Owner;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008583 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosee10f4d32012-09-15 02:48:31 +00008584 return;
8585
8586 // Because we don't have an expression for the variable, we have to set the
8587 // location explicitly here.
8588 Owner.Loc = Var->getLocation();
8589 Owner.Range = Var->getSourceRange();
8590
8591 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8592 diagnoseRetainCycle(*this, Capturer, Owner);
8593}
8594
Ted Kremenek9d084012012-12-21 08:04:28 +00008595static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8596 Expr *RHS, bool isProperty) {
8597 // Check if RHS is an Objective-C object literal, which also can get
8598 // immediately zapped in a weak reference. Note that we explicitly
8599 // allow ObjCStringLiterals, since those are designed to never really die.
8600 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008601
Ted Kremenekd3292c82012-12-21 22:46:35 +00008602 // This enum needs to match with the 'select' in
8603 // warn_objc_arc_literal_assign (off-by-1).
8604 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8605 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8606 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00008607
8608 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00008609 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00008610 << (isProperty ? 0 : 1)
8611 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008612
8613 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00008614}
8615
Ted Kremenekb29b30f2012-12-21 19:45:30 +00008616static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8617 Qualifiers::ObjCLifetime LT,
8618 Expr *RHS, bool isProperty) {
8619 // Strip off any implicit cast added to get to the one ARC-specific.
8620 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8621 if (cast->getCastKind() == CK_ARCConsumeObject) {
8622 S.Diag(Loc, diag::warn_arc_retained_assign)
8623 << (LT == Qualifiers::OCL_ExplicitNone)
8624 << (isProperty ? 0 : 1)
8625 << RHS->getSourceRange();
8626 return true;
8627 }
8628 RHS = cast->getSubExpr();
8629 }
8630
8631 if (LT == Qualifiers::OCL_Weak &&
8632 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8633 return true;
8634
8635 return false;
8636}
8637
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008638bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8639 QualType LHS, Expr *RHS) {
8640 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8641
8642 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8643 return false;
8644
8645 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8646 return true;
8647
8648 return false;
8649}
8650
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008651void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8652 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008653 QualType LHSType;
8654 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07008655 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008656 ObjCPropertyRefExpr *PRE
8657 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8658 if (PRE && !PRE->isImplicitProperty()) {
8659 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8660 if (PD)
8661 LHSType = PD->getType();
8662 }
8663
8664 if (LHSType.isNull())
8665 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00008666
8667 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8668
8669 if (LT == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008670 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose7a270482012-09-28 22:21:35 +00008671 getCurFunction()->markSafeWeakUse(LHS);
8672 }
8673
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008674 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8675 return;
Jordan Rose7a270482012-09-28 22:21:35 +00008676
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008677 // FIXME. Check for other life times.
8678 if (LT != Qualifiers::OCL_None)
8679 return;
8680
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008681 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008682 if (PRE->isImplicitProperty())
8683 return;
8684 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8685 if (!PD)
8686 return;
8687
Bill Wendlingad017fa2012-12-20 19:22:21 +00008688 unsigned Attributes = PD->getPropertyAttributes();
8689 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008690 // when 'assign' attribute was not explicitly specified
8691 // by user, ignore it and rely on property type itself
8692 // for lifetime info.
8693 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8694 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8695 LHSType->isObjCRetainableType())
8696 return;
8697
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008698 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00008699 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008700 Diag(Loc, diag::warn_arc_retained_property_assign)
8701 << RHS->getSourceRange();
8702 return;
8703 }
8704 RHS = cast->getSubExpr();
8705 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008706 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00008707 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008708 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8709 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00008710 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008711 }
8712}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008713
8714//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8715
8716namespace {
8717bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8718 SourceLocation StmtLoc,
8719 const NullStmt *Body) {
8720 // Do not warn if the body is a macro that expands to nothing, e.g:
8721 //
8722 // #define CALL(x)
8723 // if (condition)
8724 // CALL(0);
8725 //
8726 if (Body->hasLeadingEmptyMacro())
8727 return false;
8728
8729 // Get line numbers of statement and body.
8730 bool StmtLineInvalid;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008731 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008732 &StmtLineInvalid);
8733 if (StmtLineInvalid)
8734 return false;
8735
8736 bool BodyLineInvalid;
8737 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8738 &BodyLineInvalid);
8739 if (BodyLineInvalid)
8740 return false;
8741
8742 // Warn if null statement and body are on the same line.
8743 if (StmtLine != BodyLine)
8744 return false;
8745
8746 return true;
8747}
8748} // Unnamed namespace
8749
8750void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8751 const Stmt *Body,
8752 unsigned DiagID) {
8753 // Since this is a syntactic check, don't emit diagnostic for template
8754 // instantiations, this just adds noise.
8755 if (CurrentInstantiationScope)
8756 return;
8757
8758 // The body should be a null statement.
8759 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8760 if (!NBody)
8761 return;
8762
8763 // Do the usual checks.
8764 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8765 return;
8766
8767 Diag(NBody->getSemiLoc(), DiagID);
8768 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8769}
8770
8771void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8772 const Stmt *PossibleBody) {
8773 assert(!CurrentInstantiationScope); // Ensured by caller
8774
8775 SourceLocation StmtLoc;
8776 const Stmt *Body;
8777 unsigned DiagID;
8778 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8779 StmtLoc = FS->getRParenLoc();
8780 Body = FS->getBody();
8781 DiagID = diag::warn_empty_for_body;
8782 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8783 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8784 Body = WS->getBody();
8785 DiagID = diag::warn_empty_while_body;
8786 } else
8787 return; // Neither `for' nor `while'.
8788
8789 // The body should be a null statement.
8790 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8791 if (!NBody)
8792 return;
8793
8794 // Skip expensive checks if diagnostic is disabled.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008795 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008796 return;
8797
8798 // Do the usual checks.
8799 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8800 return;
8801
8802 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8803 // noise level low, emit diagnostics only if for/while is followed by a
8804 // CompoundStmt, e.g.:
8805 // for (int i = 0; i < n; i++);
8806 // {
8807 // a(i);
8808 // }
8809 // or if for/while is followed by a statement with more indentation
8810 // than for/while itself:
8811 // for (int i = 0; i < n; i++);
8812 // a(i);
8813 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8814 if (!ProbableTypo) {
8815 bool BodyColInvalid;
8816 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8817 PossibleBody->getLocStart(),
8818 &BodyColInvalid);
8819 if (BodyColInvalid)
8820 return;
8821
8822 bool StmtColInvalid;
8823 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8824 S->getLocStart(),
8825 &StmtColInvalid);
8826 if (StmtColInvalid)
8827 return;
8828
8829 if (BodyCol > StmtCol)
8830 ProbableTypo = true;
8831 }
8832
8833 if (ProbableTypo) {
8834 Diag(NBody->getSemiLoc(), DiagID);
8835 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8836 }
8837}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008838
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008839//===--- CHECK: Warn on self move with std::move. -------------------------===//
8840
8841/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8842void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8843 SourceLocation OpLoc) {
8844
8845 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8846 return;
8847
8848 if (!ActiveTemplateInstantiations.empty())
8849 return;
8850
8851 // Strip parens and casts away.
8852 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8853 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8854
8855 // Check for a call expression
8856 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8857 if (!CE || CE->getNumArgs() != 1)
8858 return;
8859
8860 // Check for a call to std::move
8861 const FunctionDecl *FD = CE->getDirectCallee();
8862 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8863 !FD->getIdentifier()->isStr("move"))
8864 return;
8865
8866 // Get argument from std::move
8867 RHSExpr = CE->getArg(0);
8868
8869 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8870 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8871
8872 // Two DeclRefExpr's, check that the decls are the same.
8873 if (LHSDeclRef && RHSDeclRef) {
8874 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8875 return;
8876 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8877 RHSDeclRef->getDecl()->getCanonicalDecl())
8878 return;
8879
8880 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8881 << LHSExpr->getSourceRange()
8882 << RHSExpr->getSourceRange();
8883 return;
8884 }
8885
8886 // Member variables require a different approach to check for self moves.
8887 // MemberExpr's are the same if every nested MemberExpr refers to the same
8888 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8889 // the base Expr's are CXXThisExpr's.
8890 const Expr *LHSBase = LHSExpr;
8891 const Expr *RHSBase = RHSExpr;
8892 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8893 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8894 if (!LHSME || !RHSME)
8895 return;
8896
8897 while (LHSME && RHSME) {
8898 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8899 RHSME->getMemberDecl()->getCanonicalDecl())
8900 return;
8901
8902 LHSBase = LHSME->getBase();
8903 RHSBase = RHSME->getBase();
8904 LHSME = dyn_cast<MemberExpr>(LHSBase);
8905 RHSME = dyn_cast<MemberExpr>(RHSBase);
8906 }
8907
8908 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8909 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8910 if (LHSDeclRef && RHSDeclRef) {
8911 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8912 return;
8913 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8914 RHSDeclRef->getDecl()->getCanonicalDecl())
8915 return;
8916
8917 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8918 << LHSExpr->getSourceRange()
8919 << RHSExpr->getSourceRange();
8920 return;
8921 }
8922
8923 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8924 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8925 << LHSExpr->getSourceRange()
8926 << RHSExpr->getSourceRange();
8927}
8928
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008929//===--- Layout compatibility ----------------------------------------------//
8930
8931namespace {
8932
8933bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8934
8935/// \brief Check if two enumeration types are layout-compatible.
8936bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8937 // C++11 [dcl.enum] p8:
8938 // Two enumeration types are layout-compatible if they have the same
8939 // underlying type.
8940 return ED1->isComplete() && ED2->isComplete() &&
8941 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8942}
8943
8944/// \brief Check if two fields are layout-compatible.
8945bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8946 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8947 return false;
8948
8949 if (Field1->isBitField() != Field2->isBitField())
8950 return false;
8951
8952 if (Field1->isBitField()) {
8953 // Make sure that the bit-fields are the same length.
8954 unsigned Bits1 = Field1->getBitWidthValue(C);
8955 unsigned Bits2 = Field2->getBitWidthValue(C);
8956
8957 if (Bits1 != Bits2)
8958 return false;
8959 }
8960
8961 return true;
8962}
8963
8964/// \brief Check if two standard-layout structs are layout-compatible.
8965/// (C++11 [class.mem] p17)
8966bool isLayoutCompatibleStruct(ASTContext &C,
8967 RecordDecl *RD1,
8968 RecordDecl *RD2) {
8969 // If both records are C++ classes, check that base classes match.
8970 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8971 // If one of records is a CXXRecordDecl we are in C++ mode,
8972 // thus the other one is a CXXRecordDecl, too.
8973 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8974 // Check number of base classes.
8975 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8976 return false;
8977
8978 // Check the base classes.
8979 for (CXXRecordDecl::base_class_const_iterator
8980 Base1 = D1CXX->bases_begin(),
8981 BaseEnd1 = D1CXX->bases_end(),
8982 Base2 = D2CXX->bases_begin();
8983 Base1 != BaseEnd1;
8984 ++Base1, ++Base2) {
8985 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8986 return false;
8987 }
8988 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8989 // If only RD2 is a C++ class, it should have zero base classes.
8990 if (D2CXX->getNumBases() > 0)
8991 return false;
8992 }
8993
8994 // Check the fields.
8995 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8996 Field2End = RD2->field_end(),
8997 Field1 = RD1->field_begin(),
8998 Field1End = RD1->field_end();
8999 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9000 if (!isLayoutCompatible(C, *Field1, *Field2))
9001 return false;
9002 }
9003 if (Field1 != Field1End || Field2 != Field2End)
9004 return false;
9005
9006 return true;
9007}
9008
9009/// \brief Check if two standard-layout unions are layout-compatible.
9010/// (C++11 [class.mem] p18)
9011bool isLayoutCompatibleUnion(ASTContext &C,
9012 RecordDecl *RD1,
9013 RecordDecl *RD2) {
9014 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07009015 for (auto *Field2 : RD2->fields())
9016 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009017
Stephen Hines651f13c2014-04-23 16:59:28 -07009018 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009019 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9020 I = UnmatchedFields.begin(),
9021 E = UnmatchedFields.end();
9022
9023 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009024 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009025 bool Result = UnmatchedFields.erase(*I);
9026 (void) Result;
9027 assert(Result);
9028 break;
9029 }
9030 }
9031 if (I == E)
9032 return false;
9033 }
9034
9035 return UnmatchedFields.empty();
9036}
9037
9038bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9039 if (RD1->isUnion() != RD2->isUnion())
9040 return false;
9041
9042 if (RD1->isUnion())
9043 return isLayoutCompatibleUnion(C, RD1, RD2);
9044 else
9045 return isLayoutCompatibleStruct(C, RD1, RD2);
9046}
9047
9048/// \brief Check if two types are layout-compatible in C++11 sense.
9049bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9050 if (T1.isNull() || T2.isNull())
9051 return false;
9052
9053 // C++11 [basic.types] p11:
9054 // If two types T1 and T2 are the same type, then T1 and T2 are
9055 // layout-compatible types.
9056 if (C.hasSameType(T1, T2))
9057 return true;
9058
9059 T1 = T1.getCanonicalType().getUnqualifiedType();
9060 T2 = T2.getCanonicalType().getUnqualifiedType();
9061
9062 const Type::TypeClass TC1 = T1->getTypeClass();
9063 const Type::TypeClass TC2 = T2->getTypeClass();
9064
9065 if (TC1 != TC2)
9066 return false;
9067
9068 if (TC1 == Type::Enum) {
9069 return isLayoutCompatible(C,
9070 cast<EnumType>(T1)->getDecl(),
9071 cast<EnumType>(T2)->getDecl());
9072 } else if (TC1 == Type::Record) {
9073 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9074 return false;
9075
9076 return isLayoutCompatible(C,
9077 cast<RecordType>(T1)->getDecl(),
9078 cast<RecordType>(T2)->getDecl());
9079 }
9080
9081 return false;
9082}
9083}
9084
9085//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9086
9087namespace {
9088/// \brief Given a type tag expression find the type tag itself.
9089///
9090/// \param TypeExpr Type tag expression, as it appears in user's code.
9091///
9092/// \param VD Declaration of an identifier that appears in a type tag.
9093///
9094/// \param MagicValue Type tag magic value.
9095bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9096 const ValueDecl **VD, uint64_t *MagicValue) {
9097 while(true) {
9098 if (!TypeExpr)
9099 return false;
9100
9101 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9102
9103 switch (TypeExpr->getStmtClass()) {
9104 case Stmt::UnaryOperatorClass: {
9105 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9106 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9107 TypeExpr = UO->getSubExpr();
9108 continue;
9109 }
9110 return false;
9111 }
9112
9113 case Stmt::DeclRefExprClass: {
9114 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9115 *VD = DRE->getDecl();
9116 return true;
9117 }
9118
9119 case Stmt::IntegerLiteralClass: {
9120 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9121 llvm::APInt MagicValueAPInt = IL->getValue();
9122 if (MagicValueAPInt.getActiveBits() <= 64) {
9123 *MagicValue = MagicValueAPInt.getZExtValue();
9124 return true;
9125 } else
9126 return false;
9127 }
9128
9129 case Stmt::BinaryConditionalOperatorClass:
9130 case Stmt::ConditionalOperatorClass: {
9131 const AbstractConditionalOperator *ACO =
9132 cast<AbstractConditionalOperator>(TypeExpr);
9133 bool Result;
9134 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9135 if (Result)
9136 TypeExpr = ACO->getTrueExpr();
9137 else
9138 TypeExpr = ACO->getFalseExpr();
9139 continue;
9140 }
9141 return false;
9142 }
9143
9144 case Stmt::BinaryOperatorClass: {
9145 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9146 if (BO->getOpcode() == BO_Comma) {
9147 TypeExpr = BO->getRHS();
9148 continue;
9149 }
9150 return false;
9151 }
9152
9153 default:
9154 return false;
9155 }
9156 }
9157}
9158
9159/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9160///
9161/// \param TypeExpr Expression that specifies a type tag.
9162///
9163/// \param MagicValues Registered magic values.
9164///
9165/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9166/// kind.
9167///
9168/// \param TypeInfo Information about the corresponding C type.
9169///
9170/// \returns true if the corresponding C type was found.
9171bool GetMatchingCType(
9172 const IdentifierInfo *ArgumentKind,
9173 const Expr *TypeExpr, const ASTContext &Ctx,
9174 const llvm::DenseMap<Sema::TypeTagMagicValue,
9175 Sema::TypeTagData> *MagicValues,
9176 bool &FoundWrongKind,
9177 Sema::TypeTagData &TypeInfo) {
9178 FoundWrongKind = false;
9179
9180 // Variable declaration that has type_tag_for_datatype attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009181 const ValueDecl *VD = nullptr;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009182
9183 uint64_t MagicValue;
9184
9185 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9186 return false;
9187
9188 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009189 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009190 if (I->getArgumentKind() != ArgumentKind) {
9191 FoundWrongKind = true;
9192 return false;
9193 }
9194 TypeInfo.Type = I->getMatchingCType();
9195 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9196 TypeInfo.MustBeNull = I->getMustBeNull();
9197 return true;
9198 }
9199 return false;
9200 }
9201
9202 if (!MagicValues)
9203 return false;
9204
9205 llvm::DenseMap<Sema::TypeTagMagicValue,
9206 Sema::TypeTagData>::const_iterator I =
9207 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9208 if (I == MagicValues->end())
9209 return false;
9210
9211 TypeInfo = I->second;
9212 return true;
9213}
9214} // unnamed namespace
9215
9216void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9217 uint64_t MagicValue, QualType Type,
9218 bool LayoutCompatible,
9219 bool MustBeNull) {
9220 if (!TypeTagForDatatypeMagicValues)
9221 TypeTagForDatatypeMagicValues.reset(
9222 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9223
9224 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9225 (*TypeTagForDatatypeMagicValues)[Magic] =
9226 TypeTagData(Type, LayoutCompatible, MustBeNull);
9227}
9228
9229namespace {
9230bool IsSameCharType(QualType T1, QualType T2) {
9231 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9232 if (!BT1)
9233 return false;
9234
9235 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9236 if (!BT2)
9237 return false;
9238
9239 BuiltinType::Kind T1Kind = BT1->getKind();
9240 BuiltinType::Kind T2Kind = BT2->getKind();
9241
9242 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9243 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9244 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9245 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9246}
9247} // unnamed namespace
9248
9249void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9250 const Expr * const *ExprArgs) {
9251 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9252 bool IsPointerAttr = Attr->getIsPointer();
9253
9254 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9255 bool FoundWrongKind;
9256 TypeTagData TypeInfo;
9257 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9258 TypeTagForDatatypeMagicValues.get(),
9259 FoundWrongKind, TypeInfo)) {
9260 if (FoundWrongKind)
9261 Diag(TypeTagExpr->getExprLoc(),
9262 diag::warn_type_tag_for_datatype_wrong_kind)
9263 << TypeTagExpr->getSourceRange();
9264 return;
9265 }
9266
9267 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9268 if (IsPointerAttr) {
9269 // Skip implicit cast of pointer to `void *' (as a function argument).
9270 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00009271 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00009272 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009273 ArgumentExpr = ICE->getSubExpr();
9274 }
9275 QualType ArgumentType = ArgumentExpr->getType();
9276
9277 // Passing a `void*' pointer shouldn't trigger a warning.
9278 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9279 return;
9280
9281 if (TypeInfo.MustBeNull) {
9282 // Type tag with matching void type requires a null pointer.
9283 if (!ArgumentExpr->isNullPointerConstant(Context,
9284 Expr::NPC_ValueDependentIsNotNull)) {
9285 Diag(ArgumentExpr->getExprLoc(),
9286 diag::warn_type_safety_null_pointer_required)
9287 << ArgumentKind->getName()
9288 << ArgumentExpr->getSourceRange()
9289 << TypeTagExpr->getSourceRange();
9290 }
9291 return;
9292 }
9293
9294 QualType RequiredType = TypeInfo.Type;
9295 if (IsPointerAttr)
9296 RequiredType = Context.getPointerType(RequiredType);
9297
9298 bool mismatch = false;
9299 if (!TypeInfo.LayoutCompatible) {
9300 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9301
9302 // C++11 [basic.fundamental] p1:
9303 // Plain char, signed char, and unsigned char are three distinct types.
9304 //
9305 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9306 // char' depending on the current char signedness mode.
9307 if (mismatch)
9308 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9309 RequiredType->getPointeeType())) ||
9310 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9311 mismatch = false;
9312 } else
9313 if (IsPointerAttr)
9314 mismatch = !isLayoutCompatible(Context,
9315 ArgumentType->getPointeeType(),
9316 RequiredType->getPointeeType());
9317 else
9318 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9319
9320 if (mismatch)
9321 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07009322 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009323 << TypeInfo.LayoutCompatible << RequiredType
9324 << ArgumentExpr->getSourceRange()
9325 << TypeTagExpr->getSourceRange();
9326}
Stephen Hines651f13c2014-04-23 16:59:28 -07009327