blob: abcccbaf18f8870c0220dd74d9d8f9219c486c2b [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;
Stephen Hines651f13c2014-04-23 16:59:28 -0700549 case llvm::Triple::x86:
550 case llvm::Triple::x86_64:
551 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
552 return ExprError();
553 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000554 default:
555 break;
556 }
557 }
558
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000559 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000560}
561
Nate Begeman61eecf52010-06-14 05:21:25 +0000562// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700563static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000564 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700565 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-11-08 01:16:11 +0000566 switch (Type.getEltType()) {
567 case NeonTypeFlags::Int8:
568 case NeonTypeFlags::Poly8:
569 return shift ? 7 : (8 << IsQuad) - 1;
570 case NeonTypeFlags::Int16:
571 case NeonTypeFlags::Poly16:
572 return shift ? 15 : (4 << IsQuad) - 1;
573 case NeonTypeFlags::Int32:
574 return shift ? 31 : (2 << IsQuad) - 1;
575 case NeonTypeFlags::Int64:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000576 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000577 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700578 case NeonTypeFlags::Poly128:
579 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-11-08 01:16:11 +0000580 case NeonTypeFlags::Float16:
581 assert(!shift && "cannot shift float types!");
582 return (4 << IsQuad) - 1;
583 case NeonTypeFlags::Float32:
584 assert(!shift && "cannot shift float types!");
585 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000586 case NeonTypeFlags::Float64:
587 assert(!shift && "cannot shift float types!");
588 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000589 }
David Blaikie7530c032012-01-17 06:56:22 +0000590 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000591}
592
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000593/// getNeonEltType - Return the QualType corresponding to the elements of
594/// the vector type specified by the NeonTypeFlags. This is used to check
595/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000596static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700597 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000598 switch (Flags.getEltType()) {
599 case NeonTypeFlags::Int8:
600 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
601 case NeonTypeFlags::Int16:
602 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
603 case NeonTypeFlags::Int32:
604 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
605 case NeonTypeFlags::Int64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700606 if (IsInt64Long)
607 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
608 else
609 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
610 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000611 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700612 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000613 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700614 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000615 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700616 return Context.UnsignedLongTy;
617 case NeonTypeFlags::Poly128:
618 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000619 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000620 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000621 case NeonTypeFlags::Float32:
622 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000623 case NeonTypeFlags::Float64:
624 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000625 }
David Blaikie7530c032012-01-17 06:56:22 +0000626 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000627}
628
Stephen Hines651f13c2014-04-23 16:59:28 -0700629bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000630 llvm::APSInt Result;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000631 uint64_t mask = 0;
632 unsigned TV = 0;
633 int PtrArgNum = -1;
634 bool HasConstPtr = false;
635 switch (BuiltinID) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700636#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000637#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700638#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000639 }
640
641 // For NEON intrinsics which are overloaded on vector element type, validate
642 // the immediate which specifies which variant to emit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700643 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000644 if (mask) {
645 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
646 return true;
647
648 TV = Result.getLimitedValue(64);
649 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
650 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Stephen Hines651f13c2014-04-23 16:59:28 -0700651 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-08-01 09:23:19 +0000652 }
653
654 if (PtrArgNum >= 0) {
655 // Check that pointer arguments have the specified type.
656 Expr *Arg = TheCall->getArg(PtrArgNum);
657 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
658 Arg = ICE->getSubExpr();
659 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
660 QualType RHSTy = RHS.get()->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700661
662 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Stephen Hines176edba2014-12-01 14:53:08 -0800663 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Stephen Hines651f13c2014-04-23 16:59:28 -0700664 bool IsInt64Long =
665 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
666 QualType EltTy =
667 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000668 if (HasConstPtr)
669 EltTy = EltTy.withConst();
670 QualType LHSTy = Context.getPointerType(EltTy);
671 AssignConvertType ConvTy;
672 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
673 if (RHS.isInvalid())
674 return true;
675 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
676 RHS.get(), AA_Assigning))
677 return true;
678 }
679
680 // For NEON intrinsics which take an immediate value as part of the
681 // instruction, range check them here.
682 unsigned i = 0, l = 0, u = 0;
683 switch (BuiltinID) {
684 default:
685 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700686#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000687#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700688#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000689 }
Tim Northoverb793f0d2013-08-01 09:23:19 +0000690
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700691 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700692}
693
694bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
695 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000696 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700697 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700698 BuiltinID == ARM::BI__builtin_arm_strex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700699 BuiltinID == ARM::BI__builtin_arm_stlex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700700 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700701 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
702 BuiltinID == AArch64::BI__builtin_arm_strex ||
703 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000704 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700705 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700706 BuiltinID == ARM::BI__builtin_arm_ldaex ||
707 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
708 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover09df2b02013-07-16 09:47:53 +0000709
710 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
711
712 // Ensure that we have the proper number of arguments.
713 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
714 return true;
715
716 // Inspect the pointer argument of the atomic builtin. This should always be
717 // a pointer type, whose element is an integral scalar or pointer type.
718 // Because it is a pointer type, we don't have to worry about any implicit
719 // casts here.
720 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
721 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
722 if (PointerArgRes.isInvalid())
723 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700724 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000725
726 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
727 if (!pointerType) {
728 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
729 << PointerArg->getType() << PointerArg->getSourceRange();
730 return true;
731 }
732
733 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
734 // task is to insert the appropriate casts into the AST. First work out just
735 // what the appropriate type is.
736 QualType ValType = pointerType->getPointeeType();
737 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
738 if (IsLdrex)
739 AddrType.addConst();
740
741 // Issue a warning if the cast is dodgy.
742 CastKind CastNeeded = CK_NoOp;
743 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
744 CastNeeded = CK_BitCast;
745 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
746 << PointerArg->getType()
747 << Context.getPointerType(AddrType)
748 << AA_Passing << PointerArg->getSourceRange();
749 }
750
751 // Finally, do the cast and replace the argument with the corrected version.
752 AddrType = Context.getPointerType(AddrType);
753 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
754 if (PointerArgRes.isInvalid())
755 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700756 PointerArg = PointerArgRes.get();
Tim Northover09df2b02013-07-16 09:47:53 +0000757
758 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
759
760 // In general, we allow ints, floats and pointers to be loaded and stored.
761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
762 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
763 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
764 << PointerArg->getType() << PointerArg->getSourceRange();
765 return true;
766 }
767
768 // But ARM doesn't have instructions to deal with 128-bit versions.
Stephen Hines651f13c2014-04-23 16:59:28 -0700769 if (Context.getTypeSize(ValType) > MaxWidth) {
770 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-07-16 09:47:53 +0000771 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
772 << PointerArg->getType() << PointerArg->getSourceRange();
773 return true;
774 }
775
776 switch (ValType.getObjCLifetime()) {
777 case Qualifiers::OCL_None:
778 case Qualifiers::OCL_ExplicitNone:
779 // okay
780 break;
781
782 case Qualifiers::OCL_Weak:
783 case Qualifiers::OCL_Strong:
784 case Qualifiers::OCL_Autoreleasing:
785 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
786 << ValType << PointerArg->getSourceRange();
787 return true;
788 }
789
790
791 if (IsLdrex) {
792 TheCall->setType(ValType);
793 return false;
794 }
795
796 // Initialize the argument to be stored.
797 ExprResult ValArg = TheCall->getArg(0);
798 InitializedEntity Entity = InitializedEntity::InitializeParameter(
799 Context, ValType, /*consume*/ false);
800 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
801 if (ValArg.isInvalid())
802 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000803 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000804
805 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
806 // but the custom checker bypasses all default analysis.
807 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000808 return false;
809}
810
Nate Begeman26a31422010-06-08 02:47:44 +0000811bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000812 llvm::APSInt Result;
813
Tim Northover09df2b02013-07-16 09:47:53 +0000814 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700815 BuiltinID == ARM::BI__builtin_arm_ldaex ||
816 BuiltinID == ARM::BI__builtin_arm_strex ||
817 BuiltinID == ARM::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700818 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000819 }
820
Stephen Hines176edba2014-12-01 14:53:08 -0800821 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
822 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
823 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
824 }
825
Stephen Hines651f13c2014-04-23 16:59:28 -0700826 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
827 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000828
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700829 // For intrinsics which take an immediate value as part of the instruction,
830 // range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000831 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000832 switch (BuiltinID) {
833 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000834 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
835 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000836 case ARM::BI__builtin_arm_vcvtr_f:
837 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000838 case ARM::BI__builtin_arm_dmb:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700839 case ARM::BI__builtin_arm_dsb:
Stephen Hines176edba2014-12-01 14:53:08 -0800840 case ARM::BI__builtin_arm_isb:
841 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700842 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000843
Nate Begeman99c40bb2010-08-03 21:32:34 +0000844 // FIXME: VFP Intrinsics should error if VFP not present.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700845 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssond406bf02009-08-16 01:56:34 +0000846}
Daniel Dunbarde454282008-10-02 18:44:07 +0000847
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700848bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Stephen Hines651f13c2014-04-23 16:59:28 -0700849 CallExpr *TheCall) {
850 llvm::APSInt Result;
851
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700852 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700853 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
854 BuiltinID == AArch64::BI__builtin_arm_strex ||
855 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700856 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
857 }
858
Stephen Hines176edba2014-12-01 14:53:08 -0800859 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
860 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
861 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
862 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
863 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
864 }
865
Stephen Hines651f13c2014-04-23 16:59:28 -0700866 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
867 return true;
868
Stephen Hines176edba2014-12-01 14:53:08 -0800869 // For intrinsics which take an immediate value as part of the instruction,
870 // range check them here.
871 unsigned i = 0, l = 0, u = 0;
872 switch (BuiltinID) {
873 default: return false;
874 case AArch64::BI__builtin_arm_dmb:
875 case AArch64::BI__builtin_arm_dsb:
876 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
877 }
878
879 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700880}
881
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000882bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
883 unsigned i = 0, l = 0, u = 0;
884 switch (BuiltinID) {
885 default: return false;
886 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
887 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000888 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
889 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
890 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
891 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
892 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700893 }
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000894
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700895 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000896}
897
Stephen Hines651f13c2014-04-23 16:59:28 -0700898bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700899 unsigned i = 0, l = 0, u = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700900 switch (BuiltinID) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700901 default: return false;
902 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700903 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
904 case X86::BI__builtin_ia32_vpermil2pd:
905 case X86::BI__builtin_ia32_vpermil2pd256:
906 case X86::BI__builtin_ia32_vpermil2ps:
907 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
908 case X86::BI__builtin_ia32_cmpb128_mask:
909 case X86::BI__builtin_ia32_cmpw128_mask:
910 case X86::BI__builtin_ia32_cmpd128_mask:
911 case X86::BI__builtin_ia32_cmpq128_mask:
912 case X86::BI__builtin_ia32_cmpb256_mask:
913 case X86::BI__builtin_ia32_cmpw256_mask:
914 case X86::BI__builtin_ia32_cmpd256_mask:
915 case X86::BI__builtin_ia32_cmpq256_mask:
916 case X86::BI__builtin_ia32_cmpb512_mask:
917 case X86::BI__builtin_ia32_cmpw512_mask:
918 case X86::BI__builtin_ia32_cmpd512_mask:
919 case X86::BI__builtin_ia32_cmpq512_mask:
920 case X86::BI__builtin_ia32_ucmpb128_mask:
921 case X86::BI__builtin_ia32_ucmpw128_mask:
922 case X86::BI__builtin_ia32_ucmpd128_mask:
923 case X86::BI__builtin_ia32_ucmpq128_mask:
924 case X86::BI__builtin_ia32_ucmpb256_mask:
925 case X86::BI__builtin_ia32_ucmpw256_mask:
926 case X86::BI__builtin_ia32_ucmpd256_mask:
927 case X86::BI__builtin_ia32_ucmpq256_mask:
928 case X86::BI__builtin_ia32_ucmpb512_mask:
929 case X86::BI__builtin_ia32_ucmpw512_mask:
930 case X86::BI__builtin_ia32_ucmpd512_mask:
931 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
932 case X86::BI__builtin_ia32_roundps:
933 case X86::BI__builtin_ia32_roundpd:
934 case X86::BI__builtin_ia32_roundps256:
935 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
936 case X86::BI__builtin_ia32_roundss:
937 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
938 case X86::BI__builtin_ia32_cmpps:
939 case X86::BI__builtin_ia32_cmpss:
940 case X86::BI__builtin_ia32_cmppd:
941 case X86::BI__builtin_ia32_cmpsd:
942 case X86::BI__builtin_ia32_cmpps256:
943 case X86::BI__builtin_ia32_cmppd256:
944 case X86::BI__builtin_ia32_cmpps512_mask:
945 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
946 case X86::BI__builtin_ia32_vpcomub:
947 case X86::BI__builtin_ia32_vpcomuw:
948 case X86::BI__builtin_ia32_vpcomud:
949 case X86::BI__builtin_ia32_vpcomuq:
950 case X86::BI__builtin_ia32_vpcomb:
951 case X86::BI__builtin_ia32_vpcomw:
952 case X86::BI__builtin_ia32_vpcomd:
953 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700954 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700955 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Stephen Hines651f13c2014-04-23 16:59:28 -0700956}
957
Richard Smith831421f2012-06-25 20:30:08 +0000958/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
959/// parameter with the FormatAttr's correct format_idx and firstDataArg.
960/// Returns true when the format fits the function and the FormatStringInfo has
961/// been populated.
962bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
963 FormatStringInfo *FSI) {
964 FSI->HasVAListArg = Format->getFirstArg() == 0;
965 FSI->FormatIdx = Format->getFormatIdx() - 1;
966 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000967
Richard Smith831421f2012-06-25 20:30:08 +0000968 // The way the format attribute works in GCC, the implicit this argument
969 // of member functions is counted. However, it doesn't appear in our own
970 // lists, so decrement format_idx in that case.
971 if (IsCXXMember) {
972 if(FSI->FormatIdx == 0)
973 return false;
974 --FSI->FormatIdx;
975 if (FSI->FirstDataArg != 0)
976 --FSI->FirstDataArg;
977 }
978 return true;
979}
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Stephen Hines651f13c2014-04-23 16:59:28 -0700981/// Checks if a the given expression evaluates to null.
982///
983/// \brief Returns true if the value evaluates to null.
984static bool CheckNonNullExpr(Sema &S,
985 const Expr *Expr) {
986 // As a special case, transparent unions initialized with zero are
987 // considered null for the purposes of the nonnull attribute.
988 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
989 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
990 if (const CompoundLiteralExpr *CLE =
991 dyn_cast<CompoundLiteralExpr>(Expr))
992 if (const InitListExpr *ILE =
993 dyn_cast<InitListExpr>(CLE->getInitializer()))
994 Expr = ILE->getInit(0);
995 }
996
997 bool Result;
998 return (!Expr->isValueDependent() &&
999 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1000 !Result);
1001}
1002
1003static void CheckNonNullArgument(Sema &S,
1004 const Expr *ArgExpr,
1005 SourceLocation CallSiteLoc) {
1006 if (CheckNonNullExpr(S, ArgExpr))
1007 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1008}
1009
Stephen Hines176edba2014-12-01 14:53:08 -08001010bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1011 FormatStringInfo FSI;
1012 if ((GetFormatStringType(Format) == FST_NSString) &&
1013 getFormatStringInfo(Format, false, &FSI)) {
1014 Idx = FSI.FormatIdx;
1015 return true;
1016 }
1017 return false;
1018}
1019/// \brief Diagnose use of %s directive in an NSString which is being passed
1020/// as formatting string to formatting method.
1021static void
1022DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1023 const NamedDecl *FDecl,
1024 Expr **Args,
1025 unsigned NumArgs) {
1026 unsigned Idx = 0;
1027 bool Format = false;
1028 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1029 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1030 Idx = 2;
1031 Format = true;
1032 }
1033 else
1034 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1035 if (S.GetFormatNSStringIdx(I, Idx)) {
1036 Format = true;
1037 break;
1038 }
1039 }
1040 if (!Format || NumArgs <= Idx)
1041 return;
1042 const Expr *FormatExpr = Args[Idx];
1043 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1044 FormatExpr = CSCE->getSubExpr();
1045 const StringLiteral *FormatString;
1046 if (const ObjCStringLiteral *OSL =
1047 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1048 FormatString = OSL->getString();
1049 else
1050 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1051 if (!FormatString)
1052 return;
1053 if (S.FormatStringHasSArg(FormatString)) {
1054 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1055 << "%s" << 1 << 1;
1056 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1057 << FDecl->getDeclName();
1058 }
1059}
1060
Stephen Hines651f13c2014-04-23 16:59:28 -07001061static void CheckNonNullArguments(Sema &S,
1062 const NamedDecl *FDecl,
Stephen Hines176edba2014-12-01 14:53:08 -08001063 ArrayRef<const Expr *> Args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001064 SourceLocation CallSiteLoc) {
1065 // Check the attributes attached to the method/function itself.
Stephen Hines176edba2014-12-01 14:53:08 -08001066 llvm::SmallBitVector NonNullArgs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001067 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001068 if (!NonNull->args_size()) {
1069 // Easy case: all pointer arguments are nonnull.
1070 for (const auto *Arg : Args)
1071 if (S.isValidPointerAttrType(Arg->getType()))
1072 CheckNonNullArgument(S, Arg, CallSiteLoc);
1073 return;
1074 }
1075
1076 for (unsigned Val : NonNull->args()) {
1077 if (Val >= Args.size())
1078 continue;
1079 if (NonNullArgs.empty())
1080 NonNullArgs.resize(Args.size());
1081 NonNullArgs.set(Val);
1082 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001083 }
1084
1085 // Check the attributes on the parameters.
1086 ArrayRef<ParmVarDecl*> parms;
1087 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1088 parms = FD->parameters();
1089 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1090 parms = MD->parameters();
1091
Stephen Hines176edba2014-12-01 14:53:08 -08001092 unsigned ArgIndex = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001093 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Stephen Hines176edba2014-12-01 14:53:08 -08001094 I != E; ++I, ++ArgIndex) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001095 const ParmVarDecl *PVD = *I;
Stephen Hines176edba2014-12-01 14:53:08 -08001096 if (PVD->hasAttr<NonNullAttr>() ||
1097 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1098 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001099 }
Stephen Hines176edba2014-12-01 14:53:08 -08001100
1101 // In case this is a variadic call, check any remaining arguments.
1102 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1103 if (NonNullArgs[ArgIndex])
1104 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001105}
1106
Richard Smith831421f2012-06-25 20:30:08 +00001107/// Handles the checks for format strings, non-POD arguments to vararg
1108/// functions, and NULL arguments passed to non-NULL parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07001109void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1110 unsigned NumParams, bool IsMemberFunction,
1111 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +00001112 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +00001113 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +00001114 if (CurContext->isDependentContext())
1115 return;
Daniel Dunbarde454282008-10-02 18:44:07 +00001116
Ted Kremenekc82faca2010-09-09 04:33:05 +00001117 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +00001118 llvm::SmallBitVector CheckedVarArgs;
1119 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001120 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001121 // Only create vector if there are format attributes.
1122 CheckedVarArgs.resize(Args.size());
1123
Stephen Hines651f13c2014-04-23 16:59:28 -07001124 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +00001125 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +00001126 }
Richard Smith0e218972013-08-05 18:49:43 +00001127 }
Richard Smith831421f2012-06-25 20:30:08 +00001128
1129 // Refuse POD arguments that weren't caught by the format string
1130 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +00001131 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001132 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001133 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +00001134 if (const Expr *Arg = Args[ArgIdx]) {
1135 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1136 checkVariadicArgument(Arg, CallType);
1137 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +00001138 }
Richard Smith0e218972013-08-05 18:49:43 +00001139 }
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Richard Trieu0538f0e2013-06-22 00:20:41 +00001141 if (FDecl) {
Stephen Hines176edba2014-12-01 14:53:08 -08001142 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001143
Richard Trieu0538f0e2013-06-22 00:20:41 +00001144 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -07001145 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1146 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00001147 }
Richard Smith831421f2012-06-25 20:30:08 +00001148}
1149
1150/// CheckConstructorCall - Check a constructor call for correctness and safety
1151/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001152void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1153 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +00001154 const FunctionProtoType *Proto,
1155 SourceLocation Loc) {
1156 VariadicCallType CallType =
1157 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -07001158 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-06-25 20:30:08 +00001159 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1160}
1161
1162/// CheckFunctionCall - Check a direct function call for various correctness
1163/// and safety properties not strictly enforced by the C type system.
1164bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1165 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +00001166 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1167 isa<CXXMethodDecl>(FDecl);
1168 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1169 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +00001170 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1171 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001172 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +00001173 Expr** Args = TheCall->getArgs();
1174 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +00001175 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +00001176 // If this is a call to a member operator, hide the first argument
1177 // from checkCall.
1178 // FIXME: Our choice of AST representation here is less than ideal.
1179 ++Args;
1180 --NumArgs;
1181 }
Stephen Hines176edba2014-12-01 14:53:08 -08001182 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith831421f2012-06-25 20:30:08 +00001183 IsMemberFunction, TheCall->getRParenLoc(),
1184 TheCall->getCallee()->getSourceRange(), CallType);
1185
1186 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1187 // None of the checks below are needed for functions that don't have
1188 // simple names (e.g., C++ conversion functions).
1189 if (!FnInfo)
1190 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001191
Stephen Hines651f13c2014-04-23 16:59:28 -07001192 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Stephen Hines176edba2014-12-01 14:53:08 -08001193 if (getLangOpts().ObjC1)
1194 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Stephen Hines651f13c2014-04-23 16:59:28 -07001195
Anna Zaks0a151a12012-01-17 00:37:07 +00001196 unsigned CMId = FDecl->getMemoryFunctionKind();
1197 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +00001198 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001199
Anna Zaksd9b859a2012-01-13 21:52:01 +00001200 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +00001201 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00001202 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +00001203 else if (CMId == Builtin::BIstrncat)
1204 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +00001205 else
Anna Zaks0a151a12012-01-17 00:37:07 +00001206 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001207
Anders Carlssond406bf02009-08-16 01:56:34 +00001208 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001209}
1210
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001211bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001212 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +00001213 VariadicCallType CallType =
1214 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001215
Dmitri Gribenko287f24d2013-05-05 19:42:09 +00001216 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +00001217 /*IsMemberFunction=*/false,
1218 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001219
1220 return false;
1221}
1222
Richard Trieuf462b012013-06-20 21:03:13 +00001223bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1224 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001225 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1226 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +00001227 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001229 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +00001230 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +00001231 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Richard Trieuf462b012013-06-20 21:03:13 +00001233 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +00001234 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +00001235 CallType = VariadicDoesNotApply;
1236 } else if (Ty->isBlockPointerType()) {
1237 CallType = VariadicBlock;
1238 } else { // Ty->isFunctionPointerType()
1239 CallType = VariadicFunction;
1240 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001241 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +00001242
Stephen Hines176edba2014-12-01 14:53:08 -08001243 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1244 TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001245 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +00001246 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -07001247
Anders Carlssond406bf02009-08-16 01:56:34 +00001248 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +00001249}
1250
Richard Trieu0538f0e2013-06-22 00:20:41 +00001251/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1252/// such as function pointers returned from functions.
1253bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001254 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu0538f0e2013-06-22 00:20:41 +00001255 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -07001256 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +00001257
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001258 checkCall(/*FDecl=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001259 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -07001260 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +00001261 TheCall->getCallee()->getSourceRange(), CallType);
1262
1263 return false;
1264}
1265
Stephen Hines651f13c2014-04-23 16:59:28 -07001266static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1267 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1268 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1269 return false;
1270
1271 switch (Op) {
1272 case AtomicExpr::AO__c11_atomic_init:
1273 llvm_unreachable("There is no ordering argument for an init");
1274
1275 case AtomicExpr::AO__c11_atomic_load:
1276 case AtomicExpr::AO__atomic_load_n:
1277 case AtomicExpr::AO__atomic_load:
1278 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1279 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1280
1281 case AtomicExpr::AO__c11_atomic_store:
1282 case AtomicExpr::AO__atomic_store:
1283 case AtomicExpr::AO__atomic_store_n:
1284 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1285 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1286 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1287
1288 default:
1289 return true;
1290 }
1291}
1292
Richard Smithff34d402012-04-12 05:08:17 +00001293ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1294 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +00001295 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +00001297
Richard Smithff34d402012-04-12 05:08:17 +00001298 // All these operations take one of the following forms:
1299 enum {
1300 // C __c11_atomic_init(A *, C)
1301 Init,
1302 // C __c11_atomic_load(A *, int)
1303 Load,
1304 // void __atomic_load(A *, CP, int)
1305 Copy,
1306 // C __c11_atomic_add(A *, M, int)
1307 Arithmetic,
1308 // C __atomic_exchange_n(A *, CP, int)
1309 Xchg,
1310 // void __atomic_exchange(A *, C *, CP, int)
1311 GNUXchg,
1312 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1313 C11CmpXchg,
1314 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1315 GNUCmpXchg
1316 } Form = Init;
1317 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1318 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1319 // where:
1320 // C is an appropriate type,
1321 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1322 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1323 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1324 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +00001325
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001326 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1327 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1328 AtomicExpr::AO__atomic_load,
1329 "need to update code for modified C11 atomics");
Richard Smithff34d402012-04-12 05:08:17 +00001330 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1331 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1332 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1333 Op == AtomicExpr::AO__atomic_store_n ||
1334 Op == AtomicExpr::AO__atomic_exchange_n ||
1335 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1336 bool IsAddSub = false;
1337
1338 switch (Op) {
1339 case AtomicExpr::AO__c11_atomic_init:
1340 Form = Init;
1341 break;
1342
1343 case AtomicExpr::AO__c11_atomic_load:
1344 case AtomicExpr::AO__atomic_load_n:
1345 Form = Load;
1346 break;
1347
1348 case AtomicExpr::AO__c11_atomic_store:
1349 case AtomicExpr::AO__atomic_load:
1350 case AtomicExpr::AO__atomic_store:
1351 case AtomicExpr::AO__atomic_store_n:
1352 Form = Copy;
1353 break;
1354
1355 case AtomicExpr::AO__c11_atomic_fetch_add:
1356 case AtomicExpr::AO__c11_atomic_fetch_sub:
1357 case AtomicExpr::AO__atomic_fetch_add:
1358 case AtomicExpr::AO__atomic_fetch_sub:
1359 case AtomicExpr::AO__atomic_add_fetch:
1360 case AtomicExpr::AO__atomic_sub_fetch:
1361 IsAddSub = true;
1362 // Fall through.
1363 case AtomicExpr::AO__c11_atomic_fetch_and:
1364 case AtomicExpr::AO__c11_atomic_fetch_or:
1365 case AtomicExpr::AO__c11_atomic_fetch_xor:
1366 case AtomicExpr::AO__atomic_fetch_and:
1367 case AtomicExpr::AO__atomic_fetch_or:
1368 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00001369 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00001370 case AtomicExpr::AO__atomic_and_fetch:
1371 case AtomicExpr::AO__atomic_or_fetch:
1372 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00001373 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +00001374 Form = Arithmetic;
1375 break;
1376
1377 case AtomicExpr::AO__c11_atomic_exchange:
1378 case AtomicExpr::AO__atomic_exchange_n:
1379 Form = Xchg;
1380 break;
1381
1382 case AtomicExpr::AO__atomic_exchange:
1383 Form = GNUXchg;
1384 break;
1385
1386 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1387 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1388 Form = C11CmpXchg;
1389 break;
1390
1391 case AtomicExpr::AO__atomic_compare_exchange:
1392 case AtomicExpr::AO__atomic_compare_exchange_n:
1393 Form = GNUCmpXchg;
1394 break;
1395 }
1396
1397 // Check we have the right number of arguments.
1398 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +00001399 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001400 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001401 << TheCall->getCallee()->getSourceRange();
1402 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001403 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1404 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001405 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001406 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001407 << TheCall->getCallee()->getSourceRange();
1408 return ExprError();
1409 }
1410
Richard Smithff34d402012-04-12 05:08:17 +00001411 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001412 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001413 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1414 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1415 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001416 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001417 << Ptr->getType() << Ptr->getSourceRange();
1418 return ExprError();
1419 }
1420
Richard Smithff34d402012-04-12 05:08:17 +00001421 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1422 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1423 QualType ValType = AtomTy; // 'C'
1424 if (IsC11) {
1425 if (!AtomTy->isAtomicType()) {
1426 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1427 << Ptr->getType() << Ptr->getSourceRange();
1428 return ExprError();
1429 }
Richard Smithbc57b102012-09-15 06:09:58 +00001430 if (AtomTy.isConstQualified()) {
1431 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1432 << Ptr->getType() << Ptr->getSourceRange();
1433 return ExprError();
1434 }
Richard Smithff34d402012-04-12 05:08:17 +00001435 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001436 }
Eli Friedman276b0612011-10-11 02:20:01 +00001437
Richard Smithff34d402012-04-12 05:08:17 +00001438 // For an arithmetic operation, the implied arithmetic must be well-formed.
1439 if (Form == Arithmetic) {
1440 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1441 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1442 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1443 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1444 return ExprError();
1445 }
1446 if (!IsAddSub && !ValType->isIntegerType()) {
1447 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1448 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1449 return ExprError();
1450 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001451 if (IsC11 && ValType->isPointerType() &&
1452 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1453 diag::err_incomplete_type)) {
1454 return ExprError();
1455 }
Richard Smithff34d402012-04-12 05:08:17 +00001456 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1457 // For __atomic_*_n operations, the value type must be a scalar integral or
1458 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001459 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001460 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1461 return ExprError();
1462 }
1463
Eli Friedmana3d727b2013-09-11 03:49:34 +00001464 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1465 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001466 // For GNU atomics, require a trivially-copyable type. This is not part of
1467 // the GNU atomics specification, but we enforce it for sanity.
1468 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001469 << Ptr->getType() << Ptr->getSourceRange();
1470 return ExprError();
1471 }
1472
Richard Smithff34d402012-04-12 05:08:17 +00001473 // FIXME: For any builtin other than a load, the ValType must not be
1474 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001475
1476 switch (ValType.getObjCLifetime()) {
1477 case Qualifiers::OCL_None:
1478 case Qualifiers::OCL_ExplicitNone:
1479 // okay
1480 break;
1481
1482 case Qualifiers::OCL_Weak:
1483 case Qualifiers::OCL_Strong:
1484 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001485 // FIXME: Can this happen? By this point, ValType should be known
1486 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001487 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1488 << ValType << Ptr->getSourceRange();
1489 return ExprError();
1490 }
1491
1492 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001493 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001494 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001495 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001496 ResultType = Context.BoolTy;
1497
Richard Smithff34d402012-04-12 05:08:17 +00001498 // The type of a parameter passed 'by value'. In the GNU atomics, such
1499 // arguments are actually passed as pointers.
1500 QualType ByValType = ValType; // 'CP'
1501 if (!IsC11 && !IsN)
1502 ByValType = Ptr->getType();
1503
Eli Friedman276b0612011-10-11 02:20:01 +00001504 // The first argument --- the pointer --- has a fixed type; we
1505 // deduce the types of the rest of the arguments accordingly. Walk
1506 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001507 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001508 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001509 if (i < NumVals[Form] + 1) {
1510 switch (i) {
1511 case 1:
1512 // The second argument is the non-atomic operand. For arithmetic, this
1513 // is always passed by value, and for a compare_exchange it is always
1514 // passed by address. For the rest, GNU uses by-address and C11 uses
1515 // by-value.
1516 assert(Form != Load);
1517 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1518 Ty = ValType;
1519 else if (Form == Copy || Form == Xchg)
1520 Ty = ByValType;
1521 else if (Form == Arithmetic)
1522 Ty = Context.getPointerDiffType();
1523 else
1524 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1525 break;
1526 case 2:
1527 // The third argument to compare_exchange / GNU exchange is a
1528 // (pointer to a) desired value.
1529 Ty = ByValType;
1530 break;
1531 case 3:
1532 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1533 Ty = Context.BoolTy;
1534 break;
1535 }
Eli Friedman276b0612011-10-11 02:20:01 +00001536 } else {
1537 // The order(s) are always converted to int.
1538 Ty = Context.IntTy;
1539 }
Richard Smithff34d402012-04-12 05:08:17 +00001540
Eli Friedman276b0612011-10-11 02:20:01 +00001541 InitializedEntity Entity =
1542 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001543 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001544 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1545 if (Arg.isInvalid())
1546 return true;
1547 TheCall->setArg(i, Arg.get());
1548 }
1549
Richard Smithff34d402012-04-12 05:08:17 +00001550 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001551 SmallVector<Expr*, 5> SubExprs;
1552 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001553 switch (Form) {
1554 case Init:
1555 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001556 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001557 break;
1558 case Load:
1559 SubExprs.push_back(TheCall->getArg(1)); // Order
1560 break;
1561 case Copy:
1562 case Arithmetic:
1563 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001564 SubExprs.push_back(TheCall->getArg(2)); // Order
1565 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001566 break;
1567 case GNUXchg:
1568 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1569 SubExprs.push_back(TheCall->getArg(3)); // Order
1570 SubExprs.push_back(TheCall->getArg(1)); // Val1
1571 SubExprs.push_back(TheCall->getArg(2)); // Val2
1572 break;
1573 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001574 SubExprs.push_back(TheCall->getArg(3)); // Order
1575 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001576 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001577 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001578 break;
1579 case GNUCmpXchg:
1580 SubExprs.push_back(TheCall->getArg(4)); // Order
1581 SubExprs.push_back(TheCall->getArg(1)); // Val1
1582 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1583 SubExprs.push_back(TheCall->getArg(2)); // Val2
1584 SubExprs.push_back(TheCall->getArg(3)); // Weak
1585 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001586 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001587
1588 if (SubExprs.size() >= 2 && Form != Init) {
1589 llvm::APSInt Result(32);
1590 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1591 !isValidOrderingForOp(Result.getSExtValue(), Op))
1592 Diag(SubExprs[1]->getLocStart(),
1593 diag::warn_atomic_op_has_invalid_memory_order)
1594 << SubExprs[1]->getSourceRange();
1595 }
1596
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001597 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1598 SubExprs, ResultType, Op,
1599 TheCall->getRParenLoc());
1600
1601 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1602 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1603 Context.AtomicUsesUnsupportedLibcall(AE))
1604 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1605 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001606
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001607 return AE;
Eli Friedman276b0612011-10-11 02:20:01 +00001608}
1609
1610
John McCall5f8d6042011-08-27 01:09:30 +00001611/// checkBuiltinArgument - Given a call to a builtin function, perform
1612/// normal type-checking on the given argument, updating the call in
1613/// place. This is useful when a builtin function requires custom
1614/// type-checking for some of its arguments but not necessarily all of
1615/// them.
1616///
1617/// Returns true on error.
1618static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1619 FunctionDecl *Fn = E->getDirectCallee();
1620 assert(Fn && "builtin call without direct callee!");
1621
1622 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1623 InitializedEntity Entity =
1624 InitializedEntity::InitializeParameter(S.Context, Param);
1625
1626 ExprResult Arg = E->getArg(0);
1627 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1628 if (Arg.isInvalid())
1629 return true;
1630
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001631 E->setArg(ArgIndex, Arg.get());
John McCall5f8d6042011-08-27 01:09:30 +00001632 return false;
1633}
1634
Chris Lattner5caa3702009-05-08 06:58:22 +00001635/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1636/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1637/// type of its first argument. The main ActOnCallExpr routines have already
1638/// promoted the types of arguments because all of these calls are prototyped as
1639/// void(...).
1640///
1641/// This function goes through and does final semantic checking for these
1642/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001643ExprResult
1644Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001645 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001646 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1647 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1648
1649 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001650 if (TheCall->getNumArgs() < 1) {
1651 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1652 << 0 << 1 << TheCall->getNumArgs()
1653 << TheCall->getCallee()->getSourceRange();
1654 return ExprError();
1655 }
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Chris Lattner5caa3702009-05-08 06:58:22 +00001657 // Inspect the first argument of the atomic builtin. This should always be
1658 // a pointer type, whose element is an integral scalar or pointer type.
1659 // Because it is a pointer type, we don't have to worry about any implicit
1660 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001661 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001662 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001663 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1664 if (FirstArgResult.isInvalid())
1665 return ExprError();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001666 FirstArg = FirstArgResult.get();
Eli Friedman8c382062012-01-23 02:35:22 +00001667 TheCall->setArg(0, FirstArg);
1668
John McCallf85e1932011-06-15 23:02:42 +00001669 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1670 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001671 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1672 << FirstArg->getType() << FirstArg->getSourceRange();
1673 return ExprError();
1674 }
Mike Stump1eb44332009-09-09 15:08:12 +00001675
John McCallf85e1932011-06-15 23:02:42 +00001676 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001677 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001678 !ValType->isBlockPointerType()) {
1679 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1680 << FirstArg->getType() << FirstArg->getSourceRange();
1681 return ExprError();
1682 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001683
John McCallf85e1932011-06-15 23:02:42 +00001684 switch (ValType.getObjCLifetime()) {
1685 case Qualifiers::OCL_None:
1686 case Qualifiers::OCL_ExplicitNone:
1687 // okay
1688 break;
1689
1690 case Qualifiers::OCL_Weak:
1691 case Qualifiers::OCL_Strong:
1692 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001693 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001694 << ValType << FirstArg->getSourceRange();
1695 return ExprError();
1696 }
1697
John McCallb45ae252011-10-05 07:41:44 +00001698 // Strip any qualifiers off ValType.
1699 ValType = ValType.getUnqualifiedType();
1700
Chandler Carruth8d13d222010-07-18 20:54:12 +00001701 // The majority of builtins return a value, but a few have special return
1702 // types, so allow them to override appropriately below.
1703 QualType ResultType = ValType;
1704
Chris Lattner5caa3702009-05-08 06:58:22 +00001705 // We need to figure out which concrete builtin this maps onto. For example,
1706 // __sync_fetch_and_add with a 2 byte object turns into
1707 // __sync_fetch_and_add_2.
1708#define BUILTIN_ROW(x) \
1709 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1710 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Chris Lattner5caa3702009-05-08 06:58:22 +00001712 static const unsigned BuiltinIndices[][5] = {
1713 BUILTIN_ROW(__sync_fetch_and_add),
1714 BUILTIN_ROW(__sync_fetch_and_sub),
1715 BUILTIN_ROW(__sync_fetch_and_or),
1716 BUILTIN_ROW(__sync_fetch_and_and),
1717 BUILTIN_ROW(__sync_fetch_and_xor),
Stephen Hines176edba2014-12-01 14:53:08 -08001718 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Chris Lattner5caa3702009-05-08 06:58:22 +00001720 BUILTIN_ROW(__sync_add_and_fetch),
1721 BUILTIN_ROW(__sync_sub_and_fetch),
1722 BUILTIN_ROW(__sync_and_and_fetch),
1723 BUILTIN_ROW(__sync_or_and_fetch),
1724 BUILTIN_ROW(__sync_xor_and_fetch),
Stephen Hines176edba2014-12-01 14:53:08 -08001725 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Chris Lattner5caa3702009-05-08 06:58:22 +00001727 BUILTIN_ROW(__sync_val_compare_and_swap),
1728 BUILTIN_ROW(__sync_bool_compare_and_swap),
1729 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001730 BUILTIN_ROW(__sync_lock_release),
1731 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001732 };
Mike Stump1eb44332009-09-09 15:08:12 +00001733#undef BUILTIN_ROW
1734
Chris Lattner5caa3702009-05-08 06:58:22 +00001735 // Determine the index of the size.
1736 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001737 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001738 case 1: SizeIndex = 0; break;
1739 case 2: SizeIndex = 1; break;
1740 case 4: SizeIndex = 2; break;
1741 case 8: SizeIndex = 3; break;
1742 case 16: SizeIndex = 4; break;
1743 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001744 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1745 << FirstArg->getType() << FirstArg->getSourceRange();
1746 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001747 }
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner5caa3702009-05-08 06:58:22 +00001749 // Each of these builtins has one pointer argument, followed by some number of
1750 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1751 // that we ignore. Find out which row of BuiltinIndices to read from as well
1752 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001753 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001754 unsigned BuiltinIndex, NumFixed = 1;
Stephen Hines176edba2014-12-01 14:53:08 -08001755 bool WarnAboutSemanticsChange = false;
Chris Lattner5caa3702009-05-08 06:58:22 +00001756 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001757 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001758 case Builtin::BI__sync_fetch_and_add:
1759 case Builtin::BI__sync_fetch_and_add_1:
1760 case Builtin::BI__sync_fetch_and_add_2:
1761 case Builtin::BI__sync_fetch_and_add_4:
1762 case Builtin::BI__sync_fetch_and_add_8:
1763 case Builtin::BI__sync_fetch_and_add_16:
1764 BuiltinIndex = 0;
1765 break;
1766
1767 case Builtin::BI__sync_fetch_and_sub:
1768 case Builtin::BI__sync_fetch_and_sub_1:
1769 case Builtin::BI__sync_fetch_and_sub_2:
1770 case Builtin::BI__sync_fetch_and_sub_4:
1771 case Builtin::BI__sync_fetch_and_sub_8:
1772 case Builtin::BI__sync_fetch_and_sub_16:
1773 BuiltinIndex = 1;
1774 break;
1775
1776 case Builtin::BI__sync_fetch_and_or:
1777 case Builtin::BI__sync_fetch_and_or_1:
1778 case Builtin::BI__sync_fetch_and_or_2:
1779 case Builtin::BI__sync_fetch_and_or_4:
1780 case Builtin::BI__sync_fetch_and_or_8:
1781 case Builtin::BI__sync_fetch_and_or_16:
1782 BuiltinIndex = 2;
1783 break;
1784
1785 case Builtin::BI__sync_fetch_and_and:
1786 case Builtin::BI__sync_fetch_and_and_1:
1787 case Builtin::BI__sync_fetch_and_and_2:
1788 case Builtin::BI__sync_fetch_and_and_4:
1789 case Builtin::BI__sync_fetch_and_and_8:
1790 case Builtin::BI__sync_fetch_and_and_16:
1791 BuiltinIndex = 3;
1792 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Douglas Gregora9766412011-11-28 16:30:08 +00001794 case Builtin::BI__sync_fetch_and_xor:
1795 case Builtin::BI__sync_fetch_and_xor_1:
1796 case Builtin::BI__sync_fetch_and_xor_2:
1797 case Builtin::BI__sync_fetch_and_xor_4:
1798 case Builtin::BI__sync_fetch_and_xor_8:
1799 case Builtin::BI__sync_fetch_and_xor_16:
1800 BuiltinIndex = 4;
1801 break;
1802
Stephen Hines176edba2014-12-01 14:53:08 -08001803 case Builtin::BI__sync_fetch_and_nand:
1804 case Builtin::BI__sync_fetch_and_nand_1:
1805 case Builtin::BI__sync_fetch_and_nand_2:
1806 case Builtin::BI__sync_fetch_and_nand_4:
1807 case Builtin::BI__sync_fetch_and_nand_8:
1808 case Builtin::BI__sync_fetch_and_nand_16:
1809 BuiltinIndex = 5;
1810 WarnAboutSemanticsChange = true;
1811 break;
1812
Douglas Gregora9766412011-11-28 16:30:08 +00001813 case Builtin::BI__sync_add_and_fetch:
1814 case Builtin::BI__sync_add_and_fetch_1:
1815 case Builtin::BI__sync_add_and_fetch_2:
1816 case Builtin::BI__sync_add_and_fetch_4:
1817 case Builtin::BI__sync_add_and_fetch_8:
1818 case Builtin::BI__sync_add_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001819 BuiltinIndex = 6;
Douglas Gregora9766412011-11-28 16:30:08 +00001820 break;
1821
1822 case Builtin::BI__sync_sub_and_fetch:
1823 case Builtin::BI__sync_sub_and_fetch_1:
1824 case Builtin::BI__sync_sub_and_fetch_2:
1825 case Builtin::BI__sync_sub_and_fetch_4:
1826 case Builtin::BI__sync_sub_and_fetch_8:
1827 case Builtin::BI__sync_sub_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001828 BuiltinIndex = 7;
Douglas Gregora9766412011-11-28 16:30:08 +00001829 break;
1830
1831 case Builtin::BI__sync_and_and_fetch:
1832 case Builtin::BI__sync_and_and_fetch_1:
1833 case Builtin::BI__sync_and_and_fetch_2:
1834 case Builtin::BI__sync_and_and_fetch_4:
1835 case Builtin::BI__sync_and_and_fetch_8:
1836 case Builtin::BI__sync_and_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001837 BuiltinIndex = 8;
Douglas Gregora9766412011-11-28 16:30:08 +00001838 break;
1839
1840 case Builtin::BI__sync_or_and_fetch:
1841 case Builtin::BI__sync_or_and_fetch_1:
1842 case Builtin::BI__sync_or_and_fetch_2:
1843 case Builtin::BI__sync_or_and_fetch_4:
1844 case Builtin::BI__sync_or_and_fetch_8:
1845 case Builtin::BI__sync_or_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001846 BuiltinIndex = 9;
Douglas Gregora9766412011-11-28 16:30:08 +00001847 break;
1848
1849 case Builtin::BI__sync_xor_and_fetch:
1850 case Builtin::BI__sync_xor_and_fetch_1:
1851 case Builtin::BI__sync_xor_and_fetch_2:
1852 case Builtin::BI__sync_xor_and_fetch_4:
1853 case Builtin::BI__sync_xor_and_fetch_8:
1854 case Builtin::BI__sync_xor_and_fetch_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001855 BuiltinIndex = 10;
1856 break;
1857
1858 case Builtin::BI__sync_nand_and_fetch:
1859 case Builtin::BI__sync_nand_and_fetch_1:
1860 case Builtin::BI__sync_nand_and_fetch_2:
1861 case Builtin::BI__sync_nand_and_fetch_4:
1862 case Builtin::BI__sync_nand_and_fetch_8:
1863 case Builtin::BI__sync_nand_and_fetch_16:
1864 BuiltinIndex = 11;
1865 WarnAboutSemanticsChange = true;
Douglas Gregora9766412011-11-28 16:30:08 +00001866 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Chris Lattner5caa3702009-05-08 06:58:22 +00001868 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001869 case Builtin::BI__sync_val_compare_and_swap_1:
1870 case Builtin::BI__sync_val_compare_and_swap_2:
1871 case Builtin::BI__sync_val_compare_and_swap_4:
1872 case Builtin::BI__sync_val_compare_and_swap_8:
1873 case Builtin::BI__sync_val_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001874 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +00001875 NumFixed = 2;
1876 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001877
Chris Lattner5caa3702009-05-08 06:58:22 +00001878 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001879 case Builtin::BI__sync_bool_compare_and_swap_1:
1880 case Builtin::BI__sync_bool_compare_and_swap_2:
1881 case Builtin::BI__sync_bool_compare_and_swap_4:
1882 case Builtin::BI__sync_bool_compare_and_swap_8:
1883 case Builtin::BI__sync_bool_compare_and_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001884 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001885 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001886 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001887 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001888
1889 case Builtin::BI__sync_lock_test_and_set:
1890 case Builtin::BI__sync_lock_test_and_set_1:
1891 case Builtin::BI__sync_lock_test_and_set_2:
1892 case Builtin::BI__sync_lock_test_and_set_4:
1893 case Builtin::BI__sync_lock_test_and_set_8:
1894 case Builtin::BI__sync_lock_test_and_set_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001895 BuiltinIndex = 14;
Douglas Gregora9766412011-11-28 16:30:08 +00001896 break;
1897
Chris Lattner5caa3702009-05-08 06:58:22 +00001898 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001899 case Builtin::BI__sync_lock_release_1:
1900 case Builtin::BI__sync_lock_release_2:
1901 case Builtin::BI__sync_lock_release_4:
1902 case Builtin::BI__sync_lock_release_8:
1903 case Builtin::BI__sync_lock_release_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001904 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +00001905 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001906 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001907 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001908
1909 case Builtin::BI__sync_swap:
1910 case Builtin::BI__sync_swap_1:
1911 case Builtin::BI__sync_swap_2:
1912 case Builtin::BI__sync_swap_4:
1913 case Builtin::BI__sync_swap_8:
1914 case Builtin::BI__sync_swap_16:
Stephen Hines176edba2014-12-01 14:53:08 -08001915 BuiltinIndex = 16;
Douglas Gregora9766412011-11-28 16:30:08 +00001916 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Chris Lattner5caa3702009-05-08 06:58:22 +00001919 // Now that we know how many fixed arguments we expect, first check that we
1920 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001921 if (TheCall->getNumArgs() < 1+NumFixed) {
1922 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1923 << 0 << 1+NumFixed << TheCall->getNumArgs()
1924 << TheCall->getCallee()->getSourceRange();
1925 return ExprError();
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Stephen Hines176edba2014-12-01 14:53:08 -08001928 if (WarnAboutSemanticsChange) {
1929 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1930 << TheCall->getCallee()->getSourceRange();
1931 }
1932
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001933 // Get the decl for the concrete builtin from this, we can tell what the
1934 // concrete integer type we should convert to is.
1935 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1936 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001937 FunctionDecl *NewBuiltinDecl;
1938 if (NewBuiltinID == BuiltinID)
1939 NewBuiltinDecl = FDecl;
1940 else {
1941 // Perform builtin lookup to avoid redeclaring it.
1942 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1943 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1944 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1945 assert(Res.getFoundDecl());
1946 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001947 if (!NewBuiltinDecl)
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001948 return ExprError();
1949 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001950
John McCallf871d0c2010-08-07 06:22:56 +00001951 // The first argument --- the pointer --- has a fixed type; we
1952 // deduce the types of the rest of the arguments accordingly. Walk
1953 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001954 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001955 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Chris Lattner5caa3702009-05-08 06:58:22 +00001957 // GCC does an implicit conversion to the pointer or integer ValType. This
1958 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001959 // Initialize the argument.
1960 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1961 ValType, /*consume*/ false);
1962 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001963 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001964 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Chris Lattner5caa3702009-05-08 06:58:22 +00001966 // Okay, we have something that *can* be converted to the right type. Check
1967 // to see if there is a potentially weird extension going on here. This can
1968 // happen when you do an atomic operation on something like an char* and
1969 // pass in 42. The 42 gets converted to char. This is even more strange
1970 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001971 // FIXME: Do this check.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001972 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +00001973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001975 ASTContext& Context = this->getASTContext();
1976
1977 // Create a new DeclRefExpr to refer to the new decl.
1978 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1979 Context,
1980 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001981 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001982 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001983 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001984 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001985 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001986 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Chris Lattner5caa3702009-05-08 06:58:22 +00001988 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001989 // FIXME: This loses syntactic information.
1990 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1991 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1992 CK_BuiltinFnToFnPtr);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001993 TheCall->setCallee(PromotedCall.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001995 // Change the result type of the call to match the original value type. This
1996 // is arbitrary, but the codegen for these builtins ins design to handle it
1997 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001998 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001999
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002000 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00002001}
2002
Chris Lattner69039812009-02-18 06:01:06 +00002003/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00002004/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00002005/// Note: It might also make sense to do the UTF-16 conversion here (would
2006/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00002007bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00002008 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002009 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2010
Douglas Gregor5cee1192011-07-27 05:40:30 +00002011 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002012 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2013 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00002014 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002017 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002018 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002019 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002020 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00002021 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00002022 UTF16 *ToPtr = &ToBuf[0];
2023
2024 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2025 &ToPtr, ToPtr + NumBytes,
2026 strictConversion);
2027 // Check for conversion failure.
2028 if (Result != conversionOK)
2029 Diag(Arg->getLocStart(),
2030 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2031 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00002032 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00002033}
2034
Chris Lattnerc27c6652007-12-20 00:05:45 +00002035/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2036/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00002037bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2038 Expr *Fn = TheCall->getCallee();
2039 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00002040 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002041 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002042 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2043 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00002044 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002045 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00002046 return true;
2047 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00002048
2049 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00002050 return Diag(TheCall->getLocEnd(),
2051 diag::err_typecheck_call_too_few_args_at_least)
2052 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00002053 }
2054
John McCall5f8d6042011-08-27 01:09:30 +00002055 // Type-check the first argument normally.
2056 if (checkBuiltinArgument(*this, TheCall, 0))
2057 return true;
2058
Chris Lattnerc27c6652007-12-20 00:05:45 +00002059 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00002060 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00002061 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002062 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00002063 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00002064 else if (FunctionDecl *FD = getCurFunctionDecl())
2065 isVariadic = FD->isVariadic();
2066 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002067 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Chris Lattnerc27c6652007-12-20 00:05:45 +00002069 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00002070 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2071 return true;
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Chris Lattner30ce3442007-12-19 23:59:04 +00002074 // Verify that the second argument to the builtin is the last argument of the
2075 // current function or method.
2076 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00002077 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Nico Weberb07d4482013-05-24 23:31:57 +00002079 // These are valid if SecondArgIsLastNamedArgument is false after the next
2080 // block.
2081 QualType Type;
2082 SourceLocation ParamLoc;
2083
Anders Carlsson88cf2262008-02-11 04:20:54 +00002084 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2085 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00002086 // FIXME: This isn't correct for methods (results in bogus warning).
2087 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00002088 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00002089 if (CurBlock)
2090 LastArg = *(CurBlock->TheDecl->param_end()-1);
2091 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00002092 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002093 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002094 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00002095 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00002096
2097 Type = PV->getType();
2098 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00002099 }
2100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Chris Lattner30ce3442007-12-19 23:59:04 +00002102 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00002103 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00002104 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00002105 else if (Type->isReferenceType()) {
2106 Diag(Arg->getLocStart(),
2107 diag::warn_va_start_of_reference_type_is_undefined);
2108 Diag(ParamLoc, diag::note_parameter_type) << Type;
2109 }
2110
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00002111 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00002112 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00002113}
Chris Lattner30ce3442007-12-19 23:59:04 +00002114
Stephen Hines176edba2014-12-01 14:53:08 -08002115bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2116 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2117 // const char *named_addr);
2118
2119 Expr *Func = Call->getCallee();
2120
2121 if (Call->getNumArgs() < 3)
2122 return Diag(Call->getLocEnd(),
2123 diag::err_typecheck_call_too_few_args_at_least)
2124 << 0 /*function call*/ << 3 << Call->getNumArgs();
2125
2126 // Determine whether the current function is variadic or not.
2127 bool IsVariadic;
2128 if (BlockScopeInfo *CurBlock = getCurBlock())
2129 IsVariadic = CurBlock->TheDecl->isVariadic();
2130 else if (FunctionDecl *FD = getCurFunctionDecl())
2131 IsVariadic = FD->isVariadic();
2132 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2133 IsVariadic = MD->isVariadic();
2134 else
2135 llvm_unreachable("unexpected statement type");
2136
2137 if (!IsVariadic) {
2138 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2139 return true;
2140 }
2141
2142 // Type-check the first argument normally.
2143 if (checkBuiltinArgument(*this, Call, 0))
2144 return true;
2145
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002146 const struct {
Stephen Hines176edba2014-12-01 14:53:08 -08002147 unsigned ArgNo;
2148 QualType Type;
2149 } ArgumentTypes[] = {
2150 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2151 { 2, Context.getSizeType() },
2152 };
2153
2154 for (const auto &AT : ArgumentTypes) {
2155 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2156 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2157 continue;
2158 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2159 << Arg->getType() << AT.Type << 1 /* different class */
2160 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2161 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2162 }
2163
2164 return false;
2165}
2166
Chris Lattner1b9a0792007-12-20 00:26:33 +00002167/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2168/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00002169bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2170 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00002171 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002172 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00002173 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00002174 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002175 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002176 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002177 << SourceRange(TheCall->getArg(2)->getLocStart(),
2178 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002179
John Wiegley429bb272011-04-08 18:41:53 +00002180 ExprResult OrigArg0 = TheCall->getArg(0);
2181 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00002182
Chris Lattner1b9a0792007-12-20 00:26:33 +00002183 // Do standard promotions between the two arguments, returning their common
2184 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00002185 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00002186 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2187 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00002188
2189 // Make sure any conversions are pushed back into the call; this is
2190 // type safe since unordered compare builtins are declared as "_Bool
2191 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00002192 TheCall->setArg(0, OrigArg0.get());
2193 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002194
John Wiegley429bb272011-04-08 18:41:53 +00002195 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00002196 return false;
2197
Chris Lattner1b9a0792007-12-20 00:26:33 +00002198 // If the common type isn't a real floating type, then the arguments were
2199 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00002200 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00002201 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002202 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00002203 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2204 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Chris Lattner1b9a0792007-12-20 00:26:33 +00002206 return false;
2207}
2208
Benjamin Kramere771a7a2010-02-15 22:42:31 +00002209/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2210/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002211/// to check everything. We expect the last argument to be a floating point
2212/// value.
2213bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2214 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00002215 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00002216 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002217 if (TheCall->getNumArgs() > NumArgs)
2218 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002219 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00002220 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002221 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002222 (*(TheCall->arg_end()-1))->getLocEnd());
2223
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00002224 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Eli Friedman9ac6f622009-08-31 20:06:00 +00002226 if (OrigArg->isTypeDependent())
2227 return false;
2228
Chris Lattner81368fb2010-05-06 05:50:07 +00002229 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00002230 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00002231 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00002232 diag::err_typecheck_call_invalid_unary_fp)
2233 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Chris Lattner81368fb2010-05-06 05:50:07 +00002235 // If this is an implicit conversion from float -> double, remove it.
2236 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2237 Expr *CastArg = Cast->getSubExpr();
2238 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2239 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2240 "promotion from float to double is the only expected cast here");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002241 Cast->setSubExpr(nullptr);
Chris Lattner81368fb2010-05-06 05:50:07 +00002242 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00002243 }
2244 }
2245
Eli Friedman9ac6f622009-08-31 20:06:00 +00002246 return false;
2247}
2248
Eli Friedmand38617c2008-05-14 19:38:39 +00002249/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2250// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00002251ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002252 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002253 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00002254 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00002255 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2256 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002257
Nate Begeman37b6a572010-06-08 00:16:34 +00002258 // Determine which of the following types of shufflevector we're checking:
2259 // 1) unary, vector mask: (lhs, mask)
2260 // 2) binary, vector mask: (lhs, rhs, mask)
2261 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2262 QualType resType = TheCall->getArg(0)->getType();
2263 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00002264
Douglas Gregorcde01732009-05-19 22:10:17 +00002265 if (!TheCall->getArg(0)->isTypeDependent() &&
2266 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00002267 QualType LHSType = TheCall->getArg(0)->getType();
2268 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00002269
Craig Topperbbe759c2013-07-29 06:47:04 +00002270 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2271 return ExprError(Diag(TheCall->getLocStart(),
2272 diag::err_shufflevector_non_vector)
2273 << SourceRange(TheCall->getArg(0)->getLocStart(),
2274 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002275
Nate Begeman37b6a572010-06-08 00:16:34 +00002276 numElements = LHSType->getAs<VectorType>()->getNumElements();
2277 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Nate Begeman37b6a572010-06-08 00:16:34 +00002279 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2280 // with mask. If so, verify that RHS is an integer vector type with the
2281 // same number of elts as lhs.
2282 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00002283 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00002284 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00002285 return ExprError(Diag(TheCall->getLocStart(),
2286 diag::err_shufflevector_incompatible_vector)
2287 << SourceRange(TheCall->getArg(1)->getLocStart(),
2288 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00002289 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00002290 return ExprError(Diag(TheCall->getLocStart(),
2291 diag::err_shufflevector_incompatible_vector)
2292 << SourceRange(TheCall->getArg(0)->getLocStart(),
2293 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00002294 } else if (numElements != numResElements) {
2295 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00002296 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002297 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00002298 }
Eli Friedmand38617c2008-05-14 19:38:39 +00002299 }
2300
2301 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00002302 if (TheCall->getArg(i)->isTypeDependent() ||
2303 TheCall->getArg(i)->isValueDependent())
2304 continue;
2305
Nate Begeman37b6a572010-06-08 00:16:34 +00002306 llvm::APSInt Result(32);
2307 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2308 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002309 diag::err_shufflevector_nonconstant_argument)
2310 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002311
Craig Topper6f4f8082013-08-03 17:40:38 +00002312 // Allow -1 which will be translated to undef in the IR.
2313 if (Result.isSigned() && Result.isAllOnesValue())
2314 continue;
2315
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002316 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002317 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00002318 diag::err_shufflevector_argument_too_large)
2319 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00002320 }
2321
Chris Lattner5f9e2722011-07-23 10:55:15 +00002322 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00002323
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00002324 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00002325 exprs.push_back(TheCall->getArg(i));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002326 TheCall->setArg(i, nullptr);
Eli Friedmand38617c2008-05-14 19:38:39 +00002327 }
2328
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002329 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2330 TheCall->getCallee()->getLocStart(),
2331 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +00002332}
Chris Lattner30ce3442007-12-19 23:59:04 +00002333
Hal Finkel414a1bd2013-09-18 03:29:45 +00002334/// SemaConvertVectorExpr - Handle __builtin_convertvector
2335ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2336 SourceLocation BuiltinLoc,
2337 SourceLocation RParenLoc) {
2338 ExprValueKind VK = VK_RValue;
2339 ExprObjectKind OK = OK_Ordinary;
2340 QualType DstTy = TInfo->getType();
2341 QualType SrcTy = E->getType();
2342
2343 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2344 return ExprError(Diag(BuiltinLoc,
2345 diag::err_convertvector_non_vector)
2346 << E->getSourceRange());
2347 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2348 return ExprError(Diag(BuiltinLoc,
2349 diag::err_convertvector_non_vector_type));
2350
2351 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2352 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2353 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2354 if (SrcElts != DstElts)
2355 return ExprError(Diag(BuiltinLoc,
2356 diag::err_convertvector_incompatible_vector)
2357 << E->getSourceRange());
2358 }
2359
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002360 return new (Context)
2361 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkel414a1bd2013-09-18 03:29:45 +00002362}
2363
Daniel Dunbar4493f792008-07-21 22:59:13 +00002364/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2365// This is declared to take (const void*, ...) and can take two
2366// optional constant int args.
2367bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002368 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002369
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002370 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00002371 return Diag(TheCall->getLocEnd(),
2372 diag::err_typecheck_call_too_many_args_at_most)
2373 << 0 /*function call*/ << 3 << NumArgs
2374 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00002375
2376 // Argument 0 is checked for us and the remaining arguments must be
2377 // constant integers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002378 for (unsigned i = 1; i != NumArgs; ++i)
2379 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher691ebc32010-04-17 02:26:23 +00002380 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Stephen Hines651f13c2014-04-23 16:59:28 -07002382 return false;
2383}
2384
Stephen Hines176edba2014-12-01 14:53:08 -08002385/// SemaBuiltinAssume - Handle __assume (MS Extension).
2386// __assume does not evaluate its arguments, and should warn if its argument
2387// has side effects.
2388bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2389 Expr *Arg = TheCall->getArg(0);
2390 if (Arg->isInstantiationDependent()) return false;
2391
2392 if (Arg->HasSideEffects(Context))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002393 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Stephen Hines176edba2014-12-01 14:53:08 -08002394 << Arg->getSourceRange()
2395 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2396
2397 return false;
2398}
2399
2400/// Handle __builtin_assume_aligned. This is declared
2401/// as (const void*, size_t, ...) and can take one optional constant int arg.
2402bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2403 unsigned NumArgs = TheCall->getNumArgs();
2404
2405 if (NumArgs > 3)
2406 return Diag(TheCall->getLocEnd(),
2407 diag::err_typecheck_call_too_many_args_at_most)
2408 << 0 /*function call*/ << 3 << NumArgs
2409 << TheCall->getSourceRange();
2410
2411 // The alignment must be a constant integer.
2412 Expr *Arg = TheCall->getArg(1);
2413
2414 // We can't check the value of a dependent argument.
2415 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2416 llvm::APSInt Result;
2417 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2418 return true;
2419
2420 if (!Result.isPowerOf2())
2421 return Diag(TheCall->getLocStart(),
2422 diag::err_alignment_not_power_of_two)
2423 << Arg->getSourceRange();
2424 }
2425
2426 if (NumArgs > 2) {
2427 ExprResult Arg(TheCall->getArg(2));
2428 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2429 Context.getSizeType(), false);
2430 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2431 if (Arg.isInvalid()) return true;
2432 TheCall->setArg(2, Arg.get());
2433 }
2434
2435 return false;
2436}
2437
Eric Christopher691ebc32010-04-17 02:26:23 +00002438/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2439/// TheCall is a constant expression.
2440bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2441 llvm::APSInt &Result) {
2442 Expr *Arg = TheCall->getArg(ArgNum);
2443 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2444 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2445
2446 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2447
2448 if (!Arg->isIntegerConstantExpr(Result, Context))
2449 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00002450 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00002451
Chris Lattner21fb98e2009-09-23 06:06:36 +00002452 return false;
2453}
2454
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002455/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2456/// TheCall is a constant expression in the range [Low, High].
2457bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2458 int Low, int High) {
Eric Christopher691ebc32010-04-17 02:26:23 +00002459 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00002460
2461 // We can't check the value of a dependent argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002462 Expr *Arg = TheCall->getArg(ArgNum);
2463 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor592a4232012-06-29 01:05:22 +00002464 return false;
2465
Eric Christopher691ebc32010-04-17 02:26:23 +00002466 // Check constant-ness first.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002467 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher691ebc32010-04-17 02:26:23 +00002468 return true;
2469
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002470 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002471 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002472 << Low << High << Arg->getSourceRange();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002473
2474 return false;
2475}
2476
Eli Friedman586d6a82009-05-03 06:04:26 +00002477/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002478/// This checks that the target supports __builtin_longjmp and
2479/// that val is a constant 1.
Eli Friedmand875fed2009-05-03 04:46:36 +00002480bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002481 if (!Context.getTargetInfo().hasSjLjLowering())
2482 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2483 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2484
Eli Friedmand875fed2009-05-03 04:46:36 +00002485 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00002486 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00002487
Eric Christopher691ebc32010-04-17 02:26:23 +00002488 // TODO: This is less than ideal. Overload this to take a value.
2489 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2490 return true;
2491
2492 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00002493 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2494 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2495
2496 return false;
2497}
2498
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002499
2500/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2501/// This checks that the target supports __builtin_setjmp.
2502bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2503 if (!Context.getTargetInfo().hasSjLjLowering())
2504 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2505 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2506 return false;
2507}
2508
Richard Smith0e218972013-08-05 18:49:43 +00002509namespace {
2510enum StringLiteralCheckType {
2511 SLCT_NotALiteral,
2512 SLCT_UncheckedLiteral,
2513 SLCT_CheckedLiteral
2514};
2515}
2516
Richard Smith831421f2012-06-25 20:30:08 +00002517// Determine if an expression is a string literal or constant string.
2518// If this function returns false on the arguments to a function expecting a
2519// format string, we will usually need to emit a warning.
2520// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00002521static StringLiteralCheckType
2522checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2523 bool HasVAListArg, unsigned format_idx,
2524 unsigned firstDataArg, Sema::FormatStringType Type,
2525 Sema::VariadicCallType CallType, bool InFunctionCall,
2526 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002527 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00002528 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00002529 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002530
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002531 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002532
Richard Smith0e218972013-08-05 18:49:43 +00002533 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00002534 // Technically -Wformat-nonliteral does not warn about this case.
2535 // The behavior of printf and friends in this case is implementation
2536 // dependent. Ideally if the format string cannot be null then
2537 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00002538 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002539
Ted Kremenekd30ef872009-01-12 23:09:09 +00002540 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002541 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002542 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00002543 // The expression is a literal if both sub-expressions were, and it was
2544 // completely checked only if both sub-expressions were checked.
2545 const AbstractConditionalOperator *C =
2546 cast<AbstractConditionalOperator>(E);
2547 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002548 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002549 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002550 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002551 if (Left == SLCT_NotALiteral)
2552 return SLCT_NotALiteral;
2553 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002554 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002555 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002556 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002557 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002558 }
2559
2560 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002561 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2562 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002563 }
2564
John McCall56ca35d2011-02-17 10:25:35 +00002565 case Stmt::OpaqueValueExprClass:
2566 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2567 E = src;
2568 goto tryAgain;
2569 }
Richard Smith831421f2012-06-25 20:30:08 +00002570 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002571
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002572 case Stmt::PredefinedExprClass:
2573 // While __func__, etc., are technically not string literals, they
2574 // cannot contain format specifiers and thus are not a security
2575 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002576 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002577
Ted Kremenek082d9362009-03-20 21:35:28 +00002578 case Stmt::DeclRefExprClass: {
2579 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Ted Kremenek082d9362009-03-20 21:35:28 +00002581 // As an exception, do not flag errors for variables binding to
2582 // const string literals.
2583 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2584 bool isConstant = false;
2585 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002586
Richard Smith0e218972013-08-05 18:49:43 +00002587 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2588 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002589 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002590 isConstant = T.isConstant(S.Context) &&
2591 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002592 } else if (T->isObjCObjectPointerType()) {
2593 // In ObjC, there is usually no "const ObjectPointer" type,
2594 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002595 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002596 }
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Ted Kremenek082d9362009-03-20 21:35:28 +00002598 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002599 if (const Expr *Init = VD->getAnyInitializer()) {
2600 // Look through initializers like const char c[] = { "foo" }
2601 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2602 if (InitList->isStringLiteralInit())
2603 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2604 }
Richard Smith0e218972013-08-05 18:49:43 +00002605 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002606 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002607 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002608 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002609 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Anders Carlssond966a552009-06-28 19:55:58 +00002612 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2613 // special check to see if the format string is a function parameter
2614 // of the function calling the printf function. If the function
2615 // has an attribute indicating it is a printf-like function, then we
2616 // should suppress warnings concerning non-literals being used in a call
2617 // to a vprintf function. For example:
2618 //
2619 // void
2620 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2621 // va_list ap;
2622 // va_start(ap, fmt);
2623 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2624 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002625 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002626 if (HasVAListArg) {
2627 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2628 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2629 int PVIndex = PV->getFunctionScopeIndex() + 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002630 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002631 // adjust for implicit parameter
2632 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2633 if (MD->isInstance())
2634 ++PVIndex;
2635 // We also check if the formats are compatible.
2636 // We can't pass a 'scanf' string to a 'printf' function.
2637 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002638 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002639 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002640 }
2641 }
2642 }
2643 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002644 }
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Richard Smith831421f2012-06-25 20:30:08 +00002646 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002647 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002648
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002649 case Stmt::CallExprClass:
2650 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002651 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002652 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2653 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2654 unsigned ArgIndex = FA->getFormatIdx();
2655 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2656 if (MD->isInstance())
2657 --ArgIndex;
2658 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Richard Smith0e218972013-08-05 18:49:43 +00002660 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002661 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002662 Type, CallType, InFunctionCall,
2663 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002664 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2665 unsigned BuiltinID = FD->getBuiltinID();
2666 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2667 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2668 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002669 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002670 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002671 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002672 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002673 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002674 }
2675 }
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Richard Smith831421f2012-06-25 20:30:08 +00002677 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002678 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002679 case Stmt::ObjCStringLiteralClass:
2680 case Stmt::StringLiteralClass: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002681 const StringLiteral *StrE = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Ted Kremenek082d9362009-03-20 21:35:28 +00002683 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002684 StrE = ObjCFExpr->getString();
2685 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002686 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Ted Kremenekd30ef872009-01-12 23:09:09 +00002688 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002689 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2690 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002691 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Richard Smith831421f2012-06-25 20:30:08 +00002694 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Ted Kremenek082d9362009-03-20 21:35:28 +00002697 default:
Richard Smith831421f2012-06-25 20:30:08 +00002698 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002699 }
2700}
2701
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002702Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002703 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002704 .Case("scanf", FST_Scanf)
2705 .Cases("printf", "printf0", FST_Printf)
2706 .Cases("NSString", "CFString", FST_NSString)
2707 .Case("strftime", FST_Strftime)
2708 .Case("strfmon", FST_Strfmon)
2709 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002710 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2711 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002712 .Default(FST_Unknown);
2713}
2714
Jordan Roseddcfbc92012-07-19 18:10:23 +00002715/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002716/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002717/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002718bool Sema::CheckFormatArguments(const FormatAttr *Format,
2719 ArrayRef<const Expr *> Args,
2720 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002721 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002722 SourceLocation Loc, SourceRange Range,
2723 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002724 FormatStringInfo FSI;
2725 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002726 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002727 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002728 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002729 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002730}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002731
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002732bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002733 bool HasVAListArg, unsigned format_idx,
2734 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002735 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002736 SourceLocation Loc, SourceRange Range,
2737 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002738 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002739 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002740 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002741 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002742 }
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002744 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Chris Lattner59907c42007-08-10 20:18:51 +00002746 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002747 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002748 // Dynamically generated format strings are difficult to
2749 // automatically vet at compile time. Requiring that format strings
2750 // are string literals: (1) permits the checking of format strings by
2751 // the compiler and thereby (2) can practically remove the source of
2752 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002753
Mike Stump1eb44332009-09-09 15:08:12 +00002754 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002755 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002756 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002757 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002758 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002759 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2760 format_idx, firstDataArg, Type, CallType,
2761 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002762 if (CT != SLCT_NotALiteral)
2763 // Literal format string found, check done!
2764 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002765
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002766 // Strftime is particular as it always uses a single 'time' argument,
2767 // so it is safe to pass a non-literal string.
2768 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002769 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002770
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002771 // Do not emit diag when the string param is a macro expansion and the
2772 // format is either NSString or CFString. This is a hack to prevent
2773 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2774 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002775 if (Type == FST_NSString &&
2776 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002777 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002778
Chris Lattner655f1412009-04-29 04:59:47 +00002779 // If there are no arguments specified, warn with -Wformat-security, otherwise
2780 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002781 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002782 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002783 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002784 << OrigFormatExpr->getSourceRange();
2785 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002786 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002787 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002788 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002789 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002790}
Ted Kremenek71895b92007-08-14 17:39:48 +00002791
Ted Kremeneke0e53132010-01-28 23:39:18 +00002792namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002793class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2794protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002795 Sema &S;
2796 const StringLiteral *FExpr;
2797 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002798 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002799 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002800 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002801 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002802 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002803 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002804 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002805 bool usesPositionalArgs;
2806 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002807 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002808 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002809 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002810public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002811 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002812 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002813 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002814 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002815 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002816 Sema::VariadicCallType callType,
2817 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002818 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002819 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2820 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002821 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002822 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002823 inFunctionCall(inFunctionCall), CallType(callType),
2824 CheckedVarArgs(CheckedVarArgs) {
2825 CoveredArgs.resize(numDataArgs);
2826 CoveredArgs.reset();
2827 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002828
Ted Kremenek07d161f2010-01-29 01:50:07 +00002829 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002830
Ted Kremenek826a3452010-07-16 02:11:22 +00002831 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002832 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002833
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002834 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002835 const analyze_format_string::FormatSpecifier &FS,
2836 const analyze_format_string::ConversionSpecifier &CS,
2837 const char *startSpecifier, unsigned specifierLen,
2838 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002839
Hans Wennborg76517422012-02-22 10:17:01 +00002840 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002841 const analyze_format_string::FormatSpecifier &FS,
2842 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002843
2844 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002845 const analyze_format_string::ConversionSpecifier &CS,
2846 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002847
Stephen Hines651f13c2014-04-23 16:59:28 -07002848 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002849
Stephen Hines651f13c2014-04-23 16:59:28 -07002850 void HandleInvalidPosition(const char *startSpecifier,
2851 unsigned specifierLen,
2852 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002853
Stephen Hines651f13c2014-04-23 16:59:28 -07002854 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002855
Stephen Hines651f13c2014-04-23 16:59:28 -07002856 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002857
Richard Trieu55733de2011-10-28 00:41:25 +00002858 template <typename Range>
2859 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2860 const Expr *ArgumentExpr,
2861 PartialDiagnostic PDiag,
2862 SourceLocation StringLoc,
2863 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002864 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002865
Ted Kremenek826a3452010-07-16 02:11:22 +00002866protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002867 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2868 const char *startSpec,
2869 unsigned specifierLen,
2870 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002871
2872 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2873 const char *startSpec,
2874 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002875
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002876 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002877 CharSourceRange getSpecifierRange(const char *startSpecifier,
2878 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002879 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002880
Ted Kremenek0d277352010-01-29 01:06:55 +00002881 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002882
2883 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2884 const analyze_format_string::ConversionSpecifier &CS,
2885 const char *startSpecifier, unsigned specifierLen,
2886 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002887
2888 template <typename Range>
2889 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2890 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002891 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002892};
2893}
2894
Ted Kremenek826a3452010-07-16 02:11:22 +00002895SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002896 return OrigFormatExpr->getSourceRange();
2897}
2898
Ted Kremenek826a3452010-07-16 02:11:22 +00002899CharSourceRange CheckFormatHandler::
2900getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002901 SourceLocation Start = getLocationOfByte(startSpecifier);
2902 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2903
2904 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002905 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002906
2907 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002908}
2909
Ted Kremenek826a3452010-07-16 02:11:22 +00002910SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002911 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002912}
2913
Ted Kremenek826a3452010-07-16 02:11:22 +00002914void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2915 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002916 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2917 getLocationOfByte(startSpecifier),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002920}
2921
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002922void CheckFormatHandler::HandleInvalidLengthModifier(
2923 const analyze_format_string::FormatSpecifier &FS,
2924 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002925 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002926 using namespace analyze_format_string;
2927
2928 const LengthModifier &LM = FS.getLengthModifier();
2929 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2930
2931 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002932 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002933 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002934 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002935 getLocationOfByte(LM.getStart()),
2936 /*IsStringLocation*/true,
2937 getSpecifierRange(startSpecifier, specifierLen));
2938
2939 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2940 << FixedLM->toString()
2941 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2942
2943 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002944 FixItHint Hint;
2945 if (DiagID == diag::warn_format_nonsensical_length)
2946 Hint = FixItHint::CreateRemoval(LMRange);
2947
2948 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002949 getLocationOfByte(LM.getStart()),
2950 /*IsStringLocation*/true,
2951 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002952 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002953 }
2954}
2955
Hans Wennborg76517422012-02-22 10:17:01 +00002956void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002957 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002958 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002959 using namespace analyze_format_string;
2960
2961 const LengthModifier &LM = FS.getLengthModifier();
2962 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2963
2964 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002965 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002966 if (FixedLM) {
2967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2968 << LM.toString() << 0,
2969 getLocationOfByte(LM.getStart()),
2970 /*IsStringLocation*/true,
2971 getSpecifierRange(startSpecifier, specifierLen));
2972
2973 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2974 << FixedLM->toString()
2975 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2976
2977 } else {
2978 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2979 << LM.toString() << 0,
2980 getLocationOfByte(LM.getStart()),
2981 /*IsStringLocation*/true,
2982 getSpecifierRange(startSpecifier, specifierLen));
2983 }
Hans Wennborg76517422012-02-22 10:17:01 +00002984}
2985
2986void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2987 const analyze_format_string::ConversionSpecifier &CS,
2988 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002989 using namespace analyze_format_string;
2990
2991 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002992 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002993 if (FixedCS) {
2994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2995 << CS.toString() << /*conversion specifier*/1,
2996 getLocationOfByte(CS.getStart()),
2997 /*IsStringLocation*/true,
2998 getSpecifierRange(startSpecifier, specifierLen));
2999
3000 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3001 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3002 << FixedCS->toString()
3003 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3004 } else {
3005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3006 << CS.toString() << /*conversion specifier*/1,
3007 getLocationOfByte(CS.getStart()),
3008 /*IsStringLocation*/true,
3009 getSpecifierRange(startSpecifier, specifierLen));
3010 }
Hans Wennborg76517422012-02-22 10:17:01 +00003011}
3012
Hans Wennborgf8562642012-03-09 10:10:54 +00003013void CheckFormatHandler::HandlePosition(const char *startPos,
3014 unsigned posLen) {
3015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3016 getLocationOfByte(startPos),
3017 /*IsStringLocation*/true,
3018 getSpecifierRange(startPos, posLen));
3019}
3020
Ted Kremenekefaff192010-02-27 01:41:03 +00003021void
Ted Kremenek826a3452010-07-16 02:11:22 +00003022CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3023 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00003024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3025 << (unsigned) p,
3026 getLocationOfByte(startPos), /*IsStringLocation*/true,
3027 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00003028}
3029
Ted Kremenek826a3452010-07-16 02:11:22 +00003030void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00003031 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00003032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3033 getLocationOfByte(startPos),
3034 /*IsStringLocation*/true,
3035 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00003036}
3037
Ted Kremenek826a3452010-07-16 02:11:22 +00003038void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00003039 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00003040 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00003041 EmitFormatDiagnostic(
3042 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3043 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3044 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00003045 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003046}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003047
Jordan Rose48716662012-07-19 18:10:08 +00003048// Note that this may return NULL if there was an error parsing or building
3049// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00003050const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003051 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00003052}
3053
3054void CheckFormatHandler::DoneProcessing() {
3055 // Does the number of data arguments exceed the number of
3056 // format conversions in the format string?
3057 if (!HasVAListArg) {
3058 // Find any arguments that weren't covered.
3059 CoveredArgs.flip();
3060 signed notCoveredArg = CoveredArgs.find_first();
3061 if (notCoveredArg >= 0) {
3062 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00003063 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3064 SourceLocation Loc = E->getLocStart();
3065 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3066 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3067 Loc, /*IsStringLocation*/false,
3068 getFormatStringRange());
3069 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00003070 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003071 }
3072 }
3073}
3074
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003075bool
3076CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3077 SourceLocation Loc,
3078 const char *startSpec,
3079 unsigned specifierLen,
3080 const char *csStart,
3081 unsigned csLen) {
3082
3083 bool keepGoing = true;
3084 if (argIndex < NumDataArgs) {
3085 // Consider the argument coverered, even though the specifier doesn't
3086 // make sense.
3087 CoveredArgs.set(argIndex);
3088 }
3089 else {
3090 // If argIndex exceeds the number of data arguments we
3091 // don't issue a warning because that is just a cascade of warnings (and
3092 // they may have intended '%%' anyway). We don't want to continue processing
3093 // the format string after this point, however, as we will like just get
3094 // gibberish when trying to match arguments.
3095 keepGoing = false;
3096 }
3097
Richard Trieu55733de2011-10-28 00:41:25 +00003098 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3099 << StringRef(csStart, csLen),
3100 Loc, /*IsStringLocation*/true,
3101 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003102
3103 return keepGoing;
3104}
3105
Richard Trieu55733de2011-10-28 00:41:25 +00003106void
3107CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3108 const char *startSpec,
3109 unsigned specifierLen) {
3110 EmitFormatDiagnostic(
3111 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3112 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3113}
3114
Ted Kremenek666a1972010-07-26 19:45:42 +00003115bool
3116CheckFormatHandler::CheckNumArgs(
3117 const analyze_format_string::FormatSpecifier &FS,
3118 const analyze_format_string::ConversionSpecifier &CS,
3119 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3120
3121 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00003122 PartialDiagnostic PDiag = FS.usesPositionalArg()
3123 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3124 << (argIndex+1) << NumDataArgs)
3125 : S.PDiag(diag::warn_printf_insufficient_data_args);
3126 EmitFormatDiagnostic(
3127 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3128 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00003129 return false;
3130 }
3131 return true;
3132}
3133
Richard Trieu55733de2011-10-28 00:41:25 +00003134template<typename Range>
3135void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3136 SourceLocation Loc,
3137 bool IsStringLocation,
3138 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00003139 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003140 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00003141 Loc, IsStringLocation, StringRange, FixIt);
3142}
3143
3144/// \brief If the format string is not within the funcion call, emit a note
3145/// so that the function call and string are in diagnostic messages.
3146///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00003147/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00003148/// call and only one diagnostic message will be produced. Otherwise, an
3149/// extra note will be emitted pointing to location of the format string.
3150///
3151/// \param ArgumentExpr the expression that is passed as the format string
3152/// argument in the function call. Used for getting locations when two
3153/// diagnostics are emitted.
3154///
3155/// \param PDiag the callee should already have provided any strings for the
3156/// diagnostic message. This function only adds locations and fixits
3157/// to diagnostics.
3158///
3159/// \param Loc primary location for diagnostic. If two diagnostics are
3160/// required, one will be at Loc and a new SourceLocation will be created for
3161/// the other one.
3162///
3163/// \param IsStringLocation if true, Loc points to the format string should be
3164/// used for the note. Otherwise, Loc points to the argument list and will
3165/// be used with PDiag.
3166///
3167/// \param StringRange some or all of the string to highlight. This is
3168/// templated so it can accept either a CharSourceRange or a SourceRange.
3169///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00003170/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00003171template<typename Range>
3172void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3173 const Expr *ArgumentExpr,
3174 PartialDiagnostic PDiag,
3175 SourceLocation Loc,
3176 bool IsStringLocation,
3177 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00003178 ArrayRef<FixItHint> FixIt) {
3179 if (InFunctionCall) {
3180 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3181 D << StringRange;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003182 D << FixIt;
Jordan Roseec087352012-09-05 22:56:26 +00003183 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00003184 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3185 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00003186
3187 const Sema::SemaDiagnosticBuilder &Note =
3188 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3189 diag::note_format_string_defined);
3190
3191 Note << StringRange;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003192 Note << FixIt;
Richard Trieu55733de2011-10-28 00:41:25 +00003193 }
3194}
3195
Ted Kremenek826a3452010-07-16 02:11:22 +00003196//===--- CHECK: Printf format string checking ------------------------------===//
3197
3198namespace {
3199class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00003200 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00003201public:
3202 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3203 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003204 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00003205 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003206 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003207 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003208 Sema::VariadicCallType CallType,
3209 llvm::SmallBitVector &CheckedVarArgs)
3210 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3211 numDataArgs, beg, hasVAListArg, Args,
3212 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3213 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003214 {}
3215
Stephen Hines651f13c2014-04-23 16:59:28 -07003216
Ted Kremenek826a3452010-07-16 02:11:22 +00003217 bool HandleInvalidPrintfConversionSpecifier(
3218 const analyze_printf::PrintfSpecifier &FS,
3219 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003220 unsigned specifierLen) override;
3221
Ted Kremenek826a3452010-07-16 02:11:22 +00003222 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3223 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003224 unsigned specifierLen) override;
Richard Smith831421f2012-06-25 20:30:08 +00003225 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3226 const char *StartSpecifier,
3227 unsigned SpecifierLen,
3228 const Expr *E);
3229
Ted Kremenek826a3452010-07-16 02:11:22 +00003230 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3231 const char *startSpecifier, unsigned specifierLen);
3232 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3233 const analyze_printf::OptionalAmount &Amt,
3234 unsigned type,
3235 const char *startSpecifier, unsigned specifierLen);
3236 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3237 const analyze_printf::OptionalFlag &flag,
3238 const char *startSpecifier, unsigned specifierLen);
3239 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3240 const analyze_printf::OptionalFlag &ignoredFlag,
3241 const analyze_printf::OptionalFlag &flag,
3242 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00003243 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07003244 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00003245
Ted Kremenek826a3452010-07-16 02:11:22 +00003246};
3247}
3248
3249bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3250 const analyze_printf::PrintfSpecifier &FS,
3251 const char *startSpecifier,
3252 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003253 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003254 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003255
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003256 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3257 getLocationOfByte(CS.getStart()),
3258 startSpecifier, specifierLen,
3259 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00003260}
3261
Ted Kremenek826a3452010-07-16 02:11:22 +00003262bool CheckPrintfHandler::HandleAmount(
3263 const analyze_format_string::OptionalAmount &Amt,
3264 unsigned k, const char *startSpecifier,
3265 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003266
3267 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003268 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003269 unsigned argIndex = Amt.getArgIndex();
3270 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00003271 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3272 << k,
3273 getLocationOfByte(Amt.getStart()),
3274 /*IsStringLocation*/true,
3275 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003276 // Don't do any more checking. We will just emit
3277 // spurious errors.
3278 return false;
3279 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003280
Ted Kremenek0d277352010-01-29 01:06:55 +00003281 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00003282 // Although not in conformance with C99, we also allow the argument to be
3283 // an 'unsigned int' as that is a reasonably safe case. GCC also
3284 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003285 CoveredArgs.set(argIndex);
3286 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003287 if (!Arg)
3288 return false;
3289
Ted Kremenek0d277352010-01-29 01:06:55 +00003290 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003291
Hans Wennborgf3749f42012-08-07 08:11:26 +00003292 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3293 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003294
Hans Wennborgf3749f42012-08-07 08:11:26 +00003295 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00003296 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00003297 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00003298 << T << Arg->getSourceRange(),
3299 getLocationOfByte(Amt.getStart()),
3300 /*IsStringLocation*/true,
3301 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00003302 // Don't do any more checking. We will just emit
3303 // spurious errors.
3304 return false;
3305 }
3306 }
3307 }
3308 return true;
3309}
Ted Kremenek0d277352010-01-29 01:06:55 +00003310
Tom Caree4ee9662010-06-17 19:00:27 +00003311void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00003312 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003313 const analyze_printf::OptionalAmount &Amt,
3314 unsigned type,
3315 const char *startSpecifier,
3316 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003317 const analyze_printf::PrintfConversionSpecifier &CS =
3318 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00003319
Richard Trieu55733de2011-10-28 00:41:25 +00003320 FixItHint fixit =
3321 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3322 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3323 Amt.getConstantLength()))
3324 : FixItHint();
3325
3326 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3327 << type << CS.toString(),
3328 getLocationOfByte(Amt.getStart()),
3329 /*IsStringLocation*/true,
3330 getSpecifierRange(startSpecifier, specifierLen),
3331 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00003332}
3333
Ted Kremenek826a3452010-07-16 02:11:22 +00003334void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003335 const analyze_printf::OptionalFlag &flag,
3336 const char *startSpecifier,
3337 unsigned specifierLen) {
3338 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003339 const analyze_printf::PrintfConversionSpecifier &CS =
3340 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00003341 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3342 << flag.toString() << CS.toString(),
3343 getLocationOfByte(flag.getPosition()),
3344 /*IsStringLocation*/true,
3345 getSpecifierRange(startSpecifier, specifierLen),
3346 FixItHint::CreateRemoval(
3347 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003348}
3349
3350void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00003351 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00003352 const analyze_printf::OptionalFlag &ignoredFlag,
3353 const analyze_printf::OptionalFlag &flag,
3354 const char *startSpecifier,
3355 unsigned specifierLen) {
3356 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00003357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3358 << ignoredFlag.toString() << flag.toString(),
3359 getLocationOfByte(ignoredFlag.getPosition()),
3360 /*IsStringLocation*/true,
3361 getSpecifierRange(startSpecifier, specifierLen),
3362 FixItHint::CreateRemoval(
3363 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00003364}
3365
Richard Smith831421f2012-06-25 20:30:08 +00003366// Determines if the specified is a C++ class or struct containing
3367// a member with the specified name and kind (e.g. a CXXMethodDecl named
3368// "c_str()").
3369template<typename MemberKind>
3370static llvm::SmallPtrSet<MemberKind*, 1>
3371CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3372 const RecordType *RT = Ty->getAs<RecordType>();
3373 llvm::SmallPtrSet<MemberKind*, 1> Results;
3374
3375 if (!RT)
3376 return Results;
3377 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07003378 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00003379 return Results;
3380
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003381 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith831421f2012-06-25 20:30:08 +00003382 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07003383 R.suppressDiagnostics();
Richard Smith831421f2012-06-25 20:30:08 +00003384
3385 // We just need to include all members of the right kind turned up by the
3386 // filter, at this point.
3387 if (S.LookupQualifiedName(R, RT->getDecl()))
3388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3389 NamedDecl *decl = (*I)->getUnderlyingDecl();
3390 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3391 Results.insert(FK);
3392 }
3393 return Results;
3394}
3395
Stephen Hines651f13c2014-04-23 16:59:28 -07003396/// Check if we could call '.c_str()' on an object.
3397///
3398/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3399/// allow the call, or if it would be ambiguous).
3400bool Sema::hasCStrMethod(const Expr *E) {
3401 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3402 MethodSet Results =
3403 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3404 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3405 MI != ME; ++MI)
3406 if ((*MI)->getMinRequiredArguments() == 0)
3407 return true;
3408 return false;
3409}
3410
Richard Smith831421f2012-06-25 20:30:08 +00003411// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00003412// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00003413// Returns true when a c_str() conversion method is found.
3414bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07003415 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-06-25 20:30:08 +00003416 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3417
3418 MethodSet Results =
3419 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3420
3421 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3422 MI != ME; ++MI) {
3423 const CXXMethodDecl *Method = *MI;
Stephen Hines651f13c2014-04-23 16:59:28 -07003424 if (Method->getMinRequiredArguments() == 0 &&
3425 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00003426 // FIXME: Suggest parens if the expression needs them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003427 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith831421f2012-06-25 20:30:08 +00003428 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3429 << "c_str()"
3430 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3431 return true;
3432 }
3433 }
3434
3435 return false;
3436}
3437
Ted Kremeneke0e53132010-01-28 23:39:18 +00003438bool
Ted Kremenek826a3452010-07-16 02:11:22 +00003439CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00003440 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00003441 const char *startSpecifier,
3442 unsigned specifierLen) {
3443
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003444 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00003445 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003446 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00003447
Ted Kremenekbaa40062010-07-19 22:01:06 +00003448 if (FS.consumesDataArgument()) {
3449 if (atFirstArg) {
3450 atFirstArg = false;
3451 usesPositionalArgs = FS.usesPositionalArg();
3452 }
3453 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003454 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3455 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003456 return false;
3457 }
Ted Kremenek0d277352010-01-29 01:06:55 +00003458 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003459
Ted Kremenekefaff192010-02-27 01:41:03 +00003460 // First check if the field width, precision, and conversion specifier
3461 // have matching data arguments.
3462 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3463 startSpecifier, specifierLen)) {
3464 return false;
3465 }
3466
3467 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3468 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003469 return false;
3470 }
3471
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003472 if (!CS.consumesDataArgument()) {
3473 // FIXME: Technically specifying a precision or field width here
3474 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003475 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003476 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003477
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003478 // Consume the argument.
3479 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00003480 if (argIndex < NumDataArgs) {
3481 // The check to see if the argIndex is valid will come later.
3482 // We set the bit here because we may exit early from this
3483 // function if we encounter some other error.
3484 CoveredArgs.set(argIndex);
3485 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003486
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003487 // FreeBSD kernel extensions.
3488 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3489 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3490 // We need at least two arguments.
3491 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3492 return false;
3493
3494 // Claim the second argument.
3495 CoveredArgs.set(argIndex + 1);
3496
3497 // Type check the first argument (int for %b, pointer for %D)
3498 const Expr *Ex = getDataArg(argIndex);
3499 const analyze_printf::ArgType &AT =
3500 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3501 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3502 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3503 EmitFormatDiagnostic(
3504 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3505 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3506 << false << Ex->getSourceRange(),
3507 Ex->getLocStart(), /*IsStringLocation*/false,
3508 getSpecifierRange(startSpecifier, specifierLen));
3509
3510 // Type check the second argument (char * for both %b and %D)
3511 Ex = getDataArg(argIndex + 1);
3512 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3513 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3514 EmitFormatDiagnostic(
3515 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3516 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3517 << false << Ex->getSourceRange(),
3518 Ex->getLocStart(), /*IsStringLocation*/false,
3519 getSpecifierRange(startSpecifier, specifierLen));
3520
3521 return true;
3522 }
3523
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003524 // Check for using an Objective-C specific conversion specifier
3525 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00003526 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003527 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3528 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003529 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003530
Tom Caree4ee9662010-06-17 19:00:27 +00003531 // Check for invalid use of field width
3532 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00003533 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00003534 startSpecifier, specifierLen);
3535 }
3536
3537 // Check for invalid use of precision
3538 if (!FS.hasValidPrecision()) {
3539 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3540 startSpecifier, specifierLen);
3541 }
3542
3543 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00003544 if (!FS.hasValidThousandsGroupingPrefix())
3545 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003546 if (!FS.hasValidLeadingZeros())
3547 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3548 if (!FS.hasValidPlusPrefix())
3549 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003550 if (!FS.hasValidSpacePrefix())
3551 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003552 if (!FS.hasValidAlternativeForm())
3553 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3554 if (!FS.hasValidLeftJustified())
3555 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3556
3557 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003558 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3559 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3560 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003561 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3562 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3563 startSpecifier, specifierLen);
3564
3565 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003566 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003567 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3568 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003569 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003570 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003571 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003572 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3573 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003574
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003575 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3576 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3577
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003578 // The remaining checks depend on the data arguments.
3579 if (HasVAListArg)
3580 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003581
Ted Kremenek666a1972010-07-26 19:45:42 +00003582 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003583 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003584
Jordan Rose48716662012-07-19 18:10:08 +00003585 const Expr *Arg = getDataArg(argIndex);
3586 if (!Arg)
3587 return true;
3588
3589 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003590}
3591
Jordan Roseec087352012-09-05 22:56:26 +00003592static bool requiresParensToAddCast(const Expr *E) {
3593 // FIXME: We should have a general way to reason about operator
3594 // precedence and whether parens are actually needed here.
3595 // Take care of a few common cases where they aren't.
3596 const Expr *Inside = E->IgnoreImpCasts();
3597 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3598 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3599
3600 switch (Inside->getStmtClass()) {
3601 case Stmt::ArraySubscriptExprClass:
3602 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003603 case Stmt::CharacterLiteralClass:
3604 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003605 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003606 case Stmt::FloatingLiteralClass:
3607 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003608 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003609 case Stmt::ObjCArrayLiteralClass:
3610 case Stmt::ObjCBoolLiteralExprClass:
3611 case Stmt::ObjCBoxedExprClass:
3612 case Stmt::ObjCDictionaryLiteralClass:
3613 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003614 case Stmt::ObjCIvarRefExprClass:
3615 case Stmt::ObjCMessageExprClass:
3616 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003617 case Stmt::ObjCStringLiteralClass:
3618 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003619 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003620 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003621 case Stmt::UnaryOperatorClass:
3622 return false;
3623 default:
3624 return true;
3625 }
3626}
3627
Stephen Hines176edba2014-12-01 14:53:08 -08003628static std::pair<QualType, StringRef>
3629shouldNotPrintDirectly(const ASTContext &Context,
3630 QualType IntendedTy,
3631 const Expr *E) {
3632 // Use a 'while' to peel off layers of typedefs.
3633 QualType TyTy = IntendedTy;
3634 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3635 StringRef Name = UserTy->getDecl()->getName();
3636 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3637 .Case("NSInteger", Context.LongTy)
3638 .Case("NSUInteger", Context.UnsignedLongTy)
3639 .Case("SInt32", Context.IntTy)
3640 .Case("UInt32", Context.UnsignedIntTy)
3641 .Default(QualType());
3642
3643 if (!CastTy.isNull())
3644 return std::make_pair(CastTy, Name);
3645
3646 TyTy = UserTy->desugar();
3647 }
3648
3649 // Strip parens if necessary.
3650 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3651 return shouldNotPrintDirectly(Context,
3652 PE->getSubExpr()->getType(),
3653 PE->getSubExpr());
3654
3655 // If this is a conditional expression, then its result type is constructed
3656 // via usual arithmetic conversions and thus there might be no necessary
3657 // typedef sugar there. Recurse to operands to check for NSInteger &
3658 // Co. usage condition.
3659 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3660 QualType TrueTy, FalseTy;
3661 StringRef TrueName, FalseName;
3662
3663 std::tie(TrueTy, TrueName) =
3664 shouldNotPrintDirectly(Context,
3665 CO->getTrueExpr()->getType(),
3666 CO->getTrueExpr());
3667 std::tie(FalseTy, FalseName) =
3668 shouldNotPrintDirectly(Context,
3669 CO->getFalseExpr()->getType(),
3670 CO->getFalseExpr());
3671
3672 if (TrueTy == FalseTy)
3673 return std::make_pair(TrueTy, TrueName);
3674 else if (TrueTy.isNull())
3675 return std::make_pair(FalseTy, FalseName);
3676 else if (FalseTy.isNull())
3677 return std::make_pair(TrueTy, TrueName);
3678 }
3679
3680 return std::make_pair(QualType(), StringRef());
3681}
3682
Richard Smith831421f2012-06-25 20:30:08 +00003683bool
3684CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3685 const char *StartSpecifier,
3686 unsigned SpecifierLen,
3687 const Expr *E) {
3688 using namespace analyze_format_string;
3689 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003690 // Now type check the data expression that matches the
3691 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003692 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3693 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003694 if (!AT.isValid())
3695 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003696
Jordan Rose448ac3e2012-12-05 18:44:40 +00003697 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003698 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3699 ExprTy = TET->getUnderlyingExpr()->getType();
3700 }
3701
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003702 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3703
3704 if (match == analyze_printf::ArgType::Match) {
Jordan Rose614a8652012-09-05 22:56:19 +00003705 return true;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003706 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003707
Jordan Rose614a8652012-09-05 22:56:19 +00003708 // Look through argument promotions for our error message's reported type.
3709 // This includes the integral and floating promotions, but excludes array
3710 // and function pointer decay; seeing that an argument intended to be a
3711 // string has type 'char [6]' is probably more confusing than 'char *'.
3712 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3713 if (ICE->getCastKind() == CK_IntegralCast ||
3714 ICE->getCastKind() == CK_FloatingCast) {
3715 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003716 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003717
3718 // Check if we didn't match because of an implicit cast from a 'char'
3719 // or 'short' to an 'int'. This is done because printf is a varargs
3720 // function.
3721 if (ICE->getType() == S.Context.IntTy ||
3722 ICE->getType() == S.Context.UnsignedIntTy) {
3723 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003724 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003725 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003726 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003727 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003728 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3729 // Special case for 'a', which has type 'int' in C.
3730 // Note, however, that we do /not/ want to treat multibyte constants like
3731 // 'MooV' as characters! This form is deprecated but still exists.
3732 if (ExprTy == S.Context.IntTy)
3733 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3734 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003735 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003736
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003737 // Look through enums to their underlying type.
3738 bool IsEnum = false;
3739 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3740 ExprTy = EnumTy->getDecl()->getIntegerType();
3741 IsEnum = true;
3742 }
3743
Jordan Rose2cd34402012-12-05 18:44:49 +00003744 // %C in an Objective-C context prints a unichar, not a wchar_t.
3745 // If the argument is an integer of some kind, believe the %C and suggest
3746 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003747 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003748 if (ObjCContext &&
3749 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3750 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3751 !ExprTy->isCharType()) {
3752 // 'unichar' is defined as a typedef of unsigned short, but we should
3753 // prefer using the typedef if it is visible.
3754 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003755
3756 // While we are here, check if the value is an IntegerLiteral that happens
3757 // to be within the valid range.
3758 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3759 const llvm::APInt &V = IL->getValue();
3760 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3761 return true;
3762 }
3763
Jordan Rose2cd34402012-12-05 18:44:49 +00003764 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3765 Sema::LookupOrdinaryName);
3766 if (S.LookupName(Result, S.getCurScope())) {
3767 NamedDecl *ND = Result.getFoundDecl();
3768 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3769 if (TD->getUnderlyingType() == IntendedTy)
3770 IntendedTy = S.Context.getTypedefType(TD);
3771 }
3772 }
3773 }
3774
3775 // Special-case some of Darwin's platform-independence types by suggesting
3776 // casts to primitive types that are known to be large enough.
Stephen Hines176edba2014-12-01 14:53:08 -08003777 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseec087352012-09-05 22:56:26 +00003778 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003779 QualType CastTy;
3780 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3781 if (!CastTy.isNull()) {
3782 IntendedTy = CastTy;
3783 ShouldNotPrintDirectly = true;
Jordan Roseec087352012-09-05 22:56:26 +00003784 }
3785 }
3786
Jordan Rose614a8652012-09-05 22:56:19 +00003787 // We may be able to offer a FixItHint if it is a supported type.
3788 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003789 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003790 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003791
Jordan Rose614a8652012-09-05 22:56:19 +00003792 if (success) {
3793 // Get the fix string from the fixed format specifier
3794 SmallString<16> buf;
3795 llvm::raw_svector_ostream os(buf);
3796 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003797
Jordan Roseec087352012-09-05 22:56:26 +00003798 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3799
Stephen Hines176edba2014-12-01 14:53:08 -08003800 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003801 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3802 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3803 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3804 }
Jordan Rose2cd34402012-12-05 18:44:49 +00003805 // In this case, the specifier is wrong and should be changed to match
3806 // the argument.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003807 EmitFormatDiagnostic(S.PDiag(diag)
3808 << AT.getRepresentativeTypeName(S.Context)
3809 << IntendedTy << IsEnum << E->getSourceRange(),
3810 E->getLocStart(),
3811 /*IsStringLocation*/ false, SpecRange,
3812 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose2cd34402012-12-05 18:44:49 +00003813
3814 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003815 // The canonical type for formatting this value is different from the
3816 // actual type of the expression. (This occurs, for example, with Darwin's
3817 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3818 // should be printed as 'long' for 64-bit compatibility.)
3819 // Rather than emitting a normal format/argument mismatch, we want to
3820 // add a cast to the recommended type (and correct the format string
3821 // if necessary).
3822 SmallString<16> CastBuf;
3823 llvm::raw_svector_ostream CastFix(CastBuf);
3824 CastFix << "(";
3825 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3826 CastFix << ")";
3827
3828 SmallVector<FixItHint,4> Hints;
3829 if (!AT.matchesType(S.Context, IntendedTy))
3830 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3831
3832 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3833 // If there's already a cast present, just replace it.
3834 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3835 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3836
3837 } else if (!requiresParensToAddCast(E)) {
3838 // If the expression has high enough precedence,
3839 // just write the C-style cast.
3840 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3841 CastFix.str()));
3842 } else {
3843 // Otherwise, add parens around the expression as well as the cast.
3844 CastFix << "(";
3845 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3846 CastFix.str()));
3847
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003848 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseec087352012-09-05 22:56:26 +00003849 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3850 }
3851
Jordan Rose2cd34402012-12-05 18:44:49 +00003852 if (ShouldNotPrintDirectly) {
3853 // The expression has a type that should not be printed directly.
3854 // We extract the name from the typedef because we don't want to show
3855 // the underlying type in the diagnostic.
Stephen Hines176edba2014-12-01 14:53:08 -08003856 StringRef Name;
3857 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3858 Name = TypedefTy->getDecl()->getName();
3859 else
3860 Name = CastTyName;
Jordan Rose2cd34402012-12-05 18:44:49 +00003861 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003862 << Name << IntendedTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003863 << E->getSourceRange(),
3864 E->getLocStart(), /*IsStringLocation=*/false,
3865 SpecRange, Hints);
3866 } else {
3867 // In this case, the expression could be printed using a different
3868 // specifier, but we've decided that the specifier is probably correct
3869 // and we should cast instead. Just use the normal warning message.
3870 EmitFormatDiagnostic(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003871 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3872 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose2cd34402012-12-05 18:44:49 +00003873 << E->getSourceRange(),
3874 E->getLocStart(), /*IsStringLocation*/false,
3875 SpecRange, Hints);
3876 }
Jordan Roseec087352012-09-05 22:56:26 +00003877 }
Jordan Rose614a8652012-09-05 22:56:19 +00003878 } else {
3879 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3880 SpecifierLen);
3881 // Since the warning for passing non-POD types to variadic functions
3882 // was deferred until now, we emit a warning for non-POD
3883 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003884 switch (S.isValidVarArgType(ExprTy)) {
3885 case Sema::VAK_Valid:
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003886 case Sema::VAK_ValidInCXX11: {
3887 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3888 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3889 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3890 }
Richard Smith0e218972013-08-05 18:49:43 +00003891
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003892 EmitFormatDiagnostic(
3893 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3894 << IsEnum << CSR << E->getSourceRange(),
3895 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3896 break;
3897 }
Richard Smith0e218972013-08-05 18:49:43 +00003898 case Sema::VAK_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08003899 case Sema::VAK_MSVCUndefined:
Richard Smith0e218972013-08-05 18:49:43 +00003900 EmitFormatDiagnostic(
3901 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003902 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003903 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003904 << CallType
3905 << AT.getRepresentativeTypeName(S.Context)
3906 << CSR
3907 << E->getSourceRange(),
3908 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003909 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003910 break;
3911
3912 case Sema::VAK_Invalid:
3913 if (ExprTy->isObjCObjectType())
3914 EmitFormatDiagnostic(
3915 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3916 << S.getLangOpts().CPlusPlus11
3917 << ExprTy
3918 << CallType
3919 << AT.getRepresentativeTypeName(S.Context)
3920 << CSR
3921 << E->getSourceRange(),
3922 E->getLocStart(), /*IsStringLocation*/false, CSR);
3923 else
3924 // FIXME: If this is an initializer list, suggest removing the braces
3925 // or inserting a cast to the target type.
3926 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3927 << isa<InitListExpr>(E) << ExprTy << CallType
3928 << AT.getRepresentativeTypeName(S.Context)
3929 << E->getSourceRange();
3930 break;
3931 }
3932
3933 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3934 "format string specifier index out of range");
3935 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003936 }
3937
Ted Kremeneke0e53132010-01-28 23:39:18 +00003938 return true;
3939}
3940
Ted Kremenek826a3452010-07-16 02:11:22 +00003941//===--- CHECK: Scanf format string checking ------------------------------===//
3942
3943namespace {
3944class CheckScanfHandler : public CheckFormatHandler {
3945public:
3946 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3947 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003948 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003949 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003950 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003951 Sema::VariadicCallType CallType,
3952 llvm::SmallBitVector &CheckedVarArgs)
3953 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3954 numDataArgs, beg, hasVAListArg,
3955 Args, formatIdx, inFunctionCall, CallType,
3956 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003957 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003958
3959 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3960 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003961 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003962
3963 bool HandleInvalidScanfConversionSpecifier(
3964 const analyze_scanf::ScanfSpecifier &FS,
3965 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003966 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00003967
Stephen Hines651f13c2014-04-23 16:59:28 -07003968 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00003969};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003970}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003971
Ted Kremenekb7c21012010-07-16 18:28:03 +00003972void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3973 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003974 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3975 getLocationOfByte(end), /*IsStringLocation*/true,
3976 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003977}
3978
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003979bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3980 const analyze_scanf::ScanfSpecifier &FS,
3981 const char *startSpecifier,
3982 unsigned specifierLen) {
3983
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003984 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003985 FS.getConversionSpecifier();
3986
3987 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3988 getLocationOfByte(CS.getStart()),
3989 startSpecifier, specifierLen,
3990 CS.getStart(), CS.getLength());
3991}
3992
Ted Kremenek826a3452010-07-16 02:11:22 +00003993bool CheckScanfHandler::HandleScanfSpecifier(
3994 const analyze_scanf::ScanfSpecifier &FS,
3995 const char *startSpecifier,
3996 unsigned specifierLen) {
3997
3998 using namespace analyze_scanf;
3999 using namespace analyze_format_string;
4000
Ted Kremenek6ecb9502010-07-20 20:04:27 +00004001 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00004002
Ted Kremenekbaa40062010-07-19 22:01:06 +00004003 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4004 // be used to decide if we are using positional arguments consistently.
4005 if (FS.consumesDataArgument()) {
4006 if (atFirstArg) {
4007 atFirstArg = false;
4008 usesPositionalArgs = FS.usesPositionalArg();
4009 }
4010 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00004011 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4012 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00004013 return false;
4014 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004015 }
4016
4017 // Check if the field with is non-zero.
4018 const OptionalAmount &Amt = FS.getFieldWidth();
4019 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4020 if (Amt.getConstantAmount() == 0) {
4021 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4022 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00004023 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4024 getLocationOfByte(Amt.getStart()),
4025 /*IsStringLocation*/true, R,
4026 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00004027 }
4028 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004029
Ted Kremenek826a3452010-07-16 02:11:22 +00004030 if (!FS.consumesDataArgument()) {
4031 // FIXME: Technically specifying a precision or field width here
4032 // makes no sense. Worth issuing a warning at some point.
4033 return true;
4034 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004035
Ted Kremenek826a3452010-07-16 02:11:22 +00004036 // Consume the argument.
4037 unsigned argIndex = FS.getArgIndex();
4038 if (argIndex < NumDataArgs) {
4039 // The check to see if the argIndex is valid will come later.
4040 // We set the bit here because we may exit early from this
4041 // function if we encounter some other error.
4042 CoveredArgs.set(argIndex);
4043 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004044
Ted Kremenek1e51c202010-07-20 20:04:47 +00004045 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004046 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00004047 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4048 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004049 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00004050 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004051 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00004052 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4053 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00004054
Jordan Rosebbb6bb42012-09-08 04:00:03 +00004055 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4056 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4057
Ted Kremenek826a3452010-07-16 02:11:22 +00004058 // The remaining checks depend on the data arguments.
4059 if (HasVAListArg)
4060 return true;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004061
Ted Kremenek666a1972010-07-26 19:45:42 +00004062 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00004063 return false;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004064
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004065 // Check that the argument type matches the format specifier.
4066 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00004067 if (!Ex)
4068 return true;
4069
Hans Wennborg58e1e542012-08-07 08:59:46 +00004070 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004071
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004072 if (!AT.isValid()) {
4073 return true;
4074 }
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004075
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004076 analyze_format_string::ArgType::MatchKind match =
4077 AT.matchesType(S.Context, Ex->getType());
4078 if (match == analyze_format_string::ArgType::Match) {
4079 return true;
4080 }
4081
4082 ScanfSpecifier fixedFS = FS;
4083 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4084 S.getLangOpts(), S.Context);
4085
4086 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4087 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4088 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4089 }
4090
4091 if (success) {
4092 // Get the fix string from the fixed format specifier.
4093 SmallString<128> buf;
4094 llvm::raw_svector_ostream os(buf);
4095 fixedFS.toString(os);
4096
4097 EmitFormatDiagnostic(
4098 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4099 << Ex->getType() << false << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00004100 Ex->getLocStart(),
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004101 /*IsStringLocation*/ false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004102 getSpecifierRange(startSpecifier, specifierLen),
4103 FixItHint::CreateReplacement(
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004104 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4105 } else {
4106 EmitFormatDiagnostic(S.PDiag(diag)
4107 << AT.getRepresentativeTypeName(S.Context)
4108 << Ex->getType() << false << Ex->getSourceRange(),
4109 Ex->getLocStart(),
4110 /*IsStringLocation*/ false,
4111 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00004112 }
4113
Ted Kremenek826a3452010-07-16 02:11:22 +00004114 return true;
4115}
4116
4117void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00004118 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004119 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004120 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004121 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00004122 bool inFunctionCall, VariadicCallType CallType,
4123 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004124
Ted Kremeneke0e53132010-01-28 23:39:18 +00004125 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00004126 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00004127 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004128 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004129 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4130 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004131 return;
4132 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004133
Ted Kremeneke0e53132010-01-28 23:39:18 +00004134 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00004135 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00004136 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07004137 // Account for cases where the string literal is truncated in a declaration.
4138 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4139 assert(T && "String literal not of constant array type!");
4140 size_t TypeSize = T->getSize().getZExtValue();
4141 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004142 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07004143
4144 // Emit a warning if the string literal is truncated and does not contain an
4145 // embedded null character.
4146 if (TypeSize <= StrRef.size() &&
4147 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4148 CheckFormatHandler::EmitFormatDiagnostic(
4149 *this, inFunctionCall, Args[format_idx],
4150 PDiag(diag::warn_printf_format_string_not_null_terminated),
4151 FExpr->getLocStart(),
4152 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4153 return;
4154 }
4155
Ted Kremeneke0e53132010-01-28 23:39:18 +00004156 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00004157 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00004158 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00004159 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00004160 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4161 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00004162 return;
4163 }
Ted Kremenek826a3452010-07-16 02:11:22 +00004164
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004165 if (Type == FST_Printf || Type == FST_NSString ||
4166 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek826a3452010-07-16 02:11:22 +00004167 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004168 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004169 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004170 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004171
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004172 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004173 getLangOpts(),
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004174 Context.getTargetInfo(),
4175 Type == FST_FreeBSDKPrintf))
Ted Kremenek826a3452010-07-16 02:11:22 +00004176 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004177 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00004178 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00004179 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00004180 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00004181
Hans Wennborgd02deeb2011-12-15 10:25:47 +00004182 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00004183 getLangOpts(),
4184 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00004185 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00004186 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00004187}
4188
Stephen Hines176edba2014-12-01 14:53:08 -08004189bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4190 // Str - The format string. NOTE: this is NOT null-terminated!
4191 StringRef StrRef = FExpr->getString();
4192 const char *Str = StrRef.data();
4193 // Account for cases where the string literal is truncated in a declaration.
4194 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4195 assert(T && "String literal not of constant array type!");
4196 size_t TypeSize = T->getSize().getZExtValue();
4197 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4198 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4199 getLangOpts(),
4200 Context.getTargetInfo());
4201}
4202
Stephen Hines651f13c2014-04-23 16:59:28 -07004203//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4204
4205// Returns the related absolute value function that is larger, of 0 if one
4206// does not exist.
4207static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4208 switch (AbsFunction) {
4209 default:
4210 return 0;
4211
4212 case Builtin::BI__builtin_abs:
4213 return Builtin::BI__builtin_labs;
4214 case Builtin::BI__builtin_labs:
4215 return Builtin::BI__builtin_llabs;
4216 case Builtin::BI__builtin_llabs:
4217 return 0;
4218
4219 case Builtin::BI__builtin_fabsf:
4220 return Builtin::BI__builtin_fabs;
4221 case Builtin::BI__builtin_fabs:
4222 return Builtin::BI__builtin_fabsl;
4223 case Builtin::BI__builtin_fabsl:
4224 return 0;
4225
4226 case Builtin::BI__builtin_cabsf:
4227 return Builtin::BI__builtin_cabs;
4228 case Builtin::BI__builtin_cabs:
4229 return Builtin::BI__builtin_cabsl;
4230 case Builtin::BI__builtin_cabsl:
4231 return 0;
4232
4233 case Builtin::BIabs:
4234 return Builtin::BIlabs;
4235 case Builtin::BIlabs:
4236 return Builtin::BIllabs;
4237 case Builtin::BIllabs:
4238 return 0;
4239
4240 case Builtin::BIfabsf:
4241 return Builtin::BIfabs;
4242 case Builtin::BIfabs:
4243 return Builtin::BIfabsl;
4244 case Builtin::BIfabsl:
4245 return 0;
4246
4247 case Builtin::BIcabsf:
4248 return Builtin::BIcabs;
4249 case Builtin::BIcabs:
4250 return Builtin::BIcabsl;
4251 case Builtin::BIcabsl:
4252 return 0;
4253 }
4254}
4255
4256// Returns the argument type of the absolute value function.
4257static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4258 unsigned AbsType) {
4259 if (AbsType == 0)
4260 return QualType();
4261
4262 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4263 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4264 if (Error != ASTContext::GE_None)
4265 return QualType();
4266
4267 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4268 if (!FT)
4269 return QualType();
4270
4271 if (FT->getNumParams() != 1)
4272 return QualType();
4273
4274 return FT->getParamType(0);
4275}
4276
4277// Returns the best absolute value function, or zero, based on type and
4278// current absolute value function.
4279static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4280 unsigned AbsFunctionKind) {
4281 unsigned BestKind = 0;
4282 uint64_t ArgSize = Context.getTypeSize(ArgType);
4283 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4284 Kind = getLargerAbsoluteValueFunction(Kind)) {
4285 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4286 if (Context.getTypeSize(ParamType) >= ArgSize) {
4287 if (BestKind == 0)
4288 BestKind = Kind;
4289 else if (Context.hasSameType(ParamType, ArgType)) {
4290 BestKind = Kind;
4291 break;
4292 }
4293 }
4294 }
4295 return BestKind;
4296}
4297
4298enum AbsoluteValueKind {
4299 AVK_Integer,
4300 AVK_Floating,
4301 AVK_Complex
4302};
4303
4304static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4305 if (T->isIntegralOrEnumerationType())
4306 return AVK_Integer;
4307 if (T->isRealFloatingType())
4308 return AVK_Floating;
4309 if (T->isAnyComplexType())
4310 return AVK_Complex;
4311
4312 llvm_unreachable("Type not integer, floating, or complex");
4313}
4314
4315// Changes the absolute value function to a different type. Preserves whether
4316// the function is a builtin.
4317static unsigned changeAbsFunction(unsigned AbsKind,
4318 AbsoluteValueKind ValueKind) {
4319 switch (ValueKind) {
4320 case AVK_Integer:
4321 switch (AbsKind) {
4322 default:
4323 return 0;
4324 case Builtin::BI__builtin_fabsf:
4325 case Builtin::BI__builtin_fabs:
4326 case Builtin::BI__builtin_fabsl:
4327 case Builtin::BI__builtin_cabsf:
4328 case Builtin::BI__builtin_cabs:
4329 case Builtin::BI__builtin_cabsl:
4330 return Builtin::BI__builtin_abs;
4331 case Builtin::BIfabsf:
4332 case Builtin::BIfabs:
4333 case Builtin::BIfabsl:
4334 case Builtin::BIcabsf:
4335 case Builtin::BIcabs:
4336 case Builtin::BIcabsl:
4337 return Builtin::BIabs;
4338 }
4339 case AVK_Floating:
4340 switch (AbsKind) {
4341 default:
4342 return 0;
4343 case Builtin::BI__builtin_abs:
4344 case Builtin::BI__builtin_labs:
4345 case Builtin::BI__builtin_llabs:
4346 case Builtin::BI__builtin_cabsf:
4347 case Builtin::BI__builtin_cabs:
4348 case Builtin::BI__builtin_cabsl:
4349 return Builtin::BI__builtin_fabsf;
4350 case Builtin::BIabs:
4351 case Builtin::BIlabs:
4352 case Builtin::BIllabs:
4353 case Builtin::BIcabsf:
4354 case Builtin::BIcabs:
4355 case Builtin::BIcabsl:
4356 return Builtin::BIfabsf;
4357 }
4358 case AVK_Complex:
4359 switch (AbsKind) {
4360 default:
4361 return 0;
4362 case Builtin::BI__builtin_abs:
4363 case Builtin::BI__builtin_labs:
4364 case Builtin::BI__builtin_llabs:
4365 case Builtin::BI__builtin_fabsf:
4366 case Builtin::BI__builtin_fabs:
4367 case Builtin::BI__builtin_fabsl:
4368 return Builtin::BI__builtin_cabsf;
4369 case Builtin::BIabs:
4370 case Builtin::BIlabs:
4371 case Builtin::BIllabs:
4372 case Builtin::BIfabsf:
4373 case Builtin::BIfabs:
4374 case Builtin::BIfabsl:
4375 return Builtin::BIcabsf;
4376 }
4377 }
4378 llvm_unreachable("Unable to convert function");
4379}
4380
4381static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4382 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4383 if (!FnInfo)
4384 return 0;
4385
4386 switch (FDecl->getBuiltinID()) {
4387 default:
4388 return 0;
4389 case Builtin::BI__builtin_abs:
4390 case Builtin::BI__builtin_fabs:
4391 case Builtin::BI__builtin_fabsf:
4392 case Builtin::BI__builtin_fabsl:
4393 case Builtin::BI__builtin_labs:
4394 case Builtin::BI__builtin_llabs:
4395 case Builtin::BI__builtin_cabs:
4396 case Builtin::BI__builtin_cabsf:
4397 case Builtin::BI__builtin_cabsl:
4398 case Builtin::BIabs:
4399 case Builtin::BIlabs:
4400 case Builtin::BIllabs:
4401 case Builtin::BIfabs:
4402 case Builtin::BIfabsf:
4403 case Builtin::BIfabsl:
4404 case Builtin::BIcabs:
4405 case Builtin::BIcabsf:
4406 case Builtin::BIcabsl:
4407 return FDecl->getBuiltinID();
4408 }
4409 llvm_unreachable("Unknown Builtin type");
4410}
4411
4412// If the replacement is valid, emit a note with replacement function.
4413// Additionally, suggest including the proper header if not already included.
4414static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004415 unsigned AbsKind, QualType ArgType) {
4416 bool EmitHeaderHint = true;
4417 const char *HeaderName = nullptr;
4418 const char *FunctionName = nullptr;
4419 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4420 FunctionName = "std::abs";
4421 if (ArgType->isIntegralOrEnumerationType()) {
4422 HeaderName = "cstdlib";
4423 } else if (ArgType->isRealFloatingType()) {
4424 HeaderName = "cmath";
4425 } else {
4426 llvm_unreachable("Invalid Type");
Stephen Hines651f13c2014-04-23 16:59:28 -07004427 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004428
4429 // Lookup all std::abs
4430 if (NamespaceDecl *Std = S.getStdNamespace()) {
4431 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4432 R.suppressDiagnostics();
4433 S.LookupQualifiedName(R, Std);
4434
4435 for (const auto *I : R) {
4436 const FunctionDecl *FDecl = nullptr;
4437 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4438 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4439 } else {
4440 FDecl = dyn_cast<FunctionDecl>(I);
4441 }
4442 if (!FDecl)
4443 continue;
4444
4445 // Found std::abs(), check that they are the right ones.
4446 if (FDecl->getNumParams() != 1)
4447 continue;
4448
4449 // Check that the parameter type can handle the argument.
4450 QualType ParamType = FDecl->getParamDecl(0)->getType();
4451 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4452 S.Context.getTypeSize(ArgType) <=
4453 S.Context.getTypeSize(ParamType)) {
4454 // Found a function, don't need the header hint.
4455 EmitHeaderHint = false;
4456 break;
4457 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004458 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004459 }
4460 } else {
4461 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4462 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4463
4464 if (HeaderName) {
4465 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4466 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4467 R.suppressDiagnostics();
4468 S.LookupName(R, S.getCurScope());
4469
4470 if (R.isSingleResult()) {
4471 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4472 if (FD && FD->getBuiltinID() == AbsKind) {
4473 EmitHeaderHint = false;
4474 } else {
4475 return;
4476 }
4477 } else if (!R.empty()) {
4478 return;
4479 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004480 }
4481 }
4482
4483 S.Diag(Loc, diag::note_replace_abs_function)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004484 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Stephen Hines651f13c2014-04-23 16:59:28 -07004485
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004486 if (!HeaderName)
4487 return;
4488
4489 if (!EmitHeaderHint)
4490 return;
4491
Stephen Hines176edba2014-12-01 14:53:08 -08004492 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4493 << FunctionName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004494}
4495
4496static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4497 if (!FDecl)
4498 return false;
4499
4500 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4501 return false;
4502
4503 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4504
4505 while (ND && ND->isInlineNamespace()) {
4506 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004507 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004508
4509 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4510 return false;
4511
4512 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4513 return false;
4514
4515 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004516}
4517
4518// Warn when using the wrong abs() function.
4519void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4520 const FunctionDecl *FDecl,
4521 IdentifierInfo *FnInfo) {
4522 if (Call->getNumArgs() != 1)
4523 return;
4524
4525 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004526 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4527 if (AbsKind == 0 && !IsStdAbs)
Stephen Hines651f13c2014-04-23 16:59:28 -07004528 return;
4529
4530 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4531 QualType ParamType = Call->getArg(0)->getType();
4532
Stephen Hines176edba2014-12-01 14:53:08 -08004533 // Unsigned types cannot be negative. Suggest removing the absolute value
4534 // function call.
Stephen Hines651f13c2014-04-23 16:59:28 -07004535 if (ArgType->isUnsignedIntegerType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004536 const char *FunctionName =
4537 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07004538 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4539 Diag(Call->getExprLoc(), diag::note_remove_abs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004540 << FunctionName
Stephen Hines651f13c2014-04-23 16:59:28 -07004541 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4542 return;
4543 }
4544
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004545 // std::abs has overloads which prevent most of the absolute value problems
4546 // from occurring.
4547 if (IsStdAbs)
4548 return;
4549
Stephen Hines651f13c2014-04-23 16:59:28 -07004550 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4551 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4552
4553 // The argument and parameter are the same kind. Check if they are the right
4554 // size.
4555 if (ArgValueKind == ParamValueKind) {
4556 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4557 return;
4558
4559 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4560 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4561 << FDecl << ArgType << ParamType;
4562
4563 if (NewAbsKind == 0)
4564 return;
4565
4566 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004567 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004568 return;
4569 }
4570
4571 // ArgValueKind != ParamValueKind
4572 // The wrong type of absolute value function was used. Attempt to find the
4573 // proper one.
4574 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4575 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4576 if (NewAbsKind == 0)
4577 return;
4578
4579 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4580 << FDecl << ParamValueKind << ArgValueKind;
4581
4582 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004583 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07004584 return;
4585}
4586
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004587//===--- CHECK: Standard memory functions ---------------------------------===//
4588
Stephen Hines651f13c2014-04-23 16:59:28 -07004589/// \brief Takes the expression passed to the size_t parameter of functions
4590/// such as memcmp, strncat, etc and warns if it's a comparison.
4591///
4592/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4593static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4594 IdentifierInfo *FnName,
4595 SourceLocation FnLoc,
4596 SourceLocation RParenLoc) {
4597 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4598 if (!Size)
4599 return false;
4600
4601 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4602 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4603 return false;
4604
Stephen Hines651f13c2014-04-23 16:59:28 -07004605 SourceRange SizeRange = Size->getSourceRange();
4606 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4607 << SizeRange << FnName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004608 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4609 << FnName << FixItHint::CreateInsertion(
4610 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Stephen Hines651f13c2014-04-23 16:59:28 -07004611 << FixItHint::CreateRemoval(RParenLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004612 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Stephen Hines651f13c2014-04-23 16:59:28 -07004613 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004614 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4615 ")");
Stephen Hines651f13c2014-04-23 16:59:28 -07004616
4617 return true;
4618}
4619
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004620/// \brief Determine whether the given type is or contains a dynamic class type
4621/// (e.g., whether it has a vtable).
4622static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4623 bool &IsContained) {
4624 // Look through array types while ignoring qualifiers.
4625 const Type *Ty = T->getBaseElementTypeUnsafe();
4626 IsContained = false;
4627
4628 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4629 RD = RD ? RD->getDefinition() : nullptr;
4630 if (!RD)
4631 return nullptr;
4632
4633 if (RD->isDynamicClass())
4634 return RD;
4635
4636 // Check all the fields. If any bases were dynamic, the class is dynamic.
4637 // It's impossible for a class to transitively contain itself by value, so
4638 // infinite recursion is impossible.
4639 for (auto *FD : RD->fields()) {
4640 bool SubContained;
4641 if (const CXXRecordDecl *ContainedRD =
4642 getContainedDynamicClass(FD->getType(), SubContained)) {
4643 IsContained = true;
4644 return ContainedRD;
4645 }
4646 }
4647
4648 return nullptr;
Douglas Gregor2a053a32011-05-03 20:05:22 +00004649}
4650
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004651/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00004652/// otherwise returns NULL.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004653static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Webere4a1c642011-06-14 16:14:58 +00004654 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00004655 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4656 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4657 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004658
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004659 return nullptr;
Chandler Carruth000d4282011-06-16 09:09:40 +00004660}
4661
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004662/// \brief If E is a sizeof expression, returns its argument type.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004663static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004664 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4665 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4666 if (SizeOf->getKind() == clang::UETT_SizeOf)
4667 return SizeOf->getTypeOfArgument();
4668
4669 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00004670}
4671
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004672/// \brief Check for dangerous or invalid arguments to memset().
4673///
Chandler Carruth929f0132011-06-03 06:23:57 +00004674/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004675/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4676/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004677///
4678/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004679void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004680 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004681 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004682 assert(BId != 0);
4683
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004684 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004685 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004686 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004687 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004688 return;
4689
Anna Zaks0a151a12012-01-17 00:37:07 +00004690 unsigned LastArg = (BId == Builtin::BImemset ||
4691 BId == Builtin::BIstrndup ? 1 : 2);
4692 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004693 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004694
Stephen Hines651f13c2014-04-23 16:59:28 -07004695 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4696 Call->getLocStart(), Call->getRParenLoc()))
4697 return;
4698
Chandler Carruth000d4282011-06-16 09:09:40 +00004699 // We have special checking when the length is a sizeof expression.
4700 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4701 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4702 llvm::FoldingSetNodeID SizeOfArgID;
4703
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004704 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4705 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004706 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004707
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004708 QualType DestTy = Dest->getType();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004709 QualType PointeeTy;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004710 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004711 PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004712
Chandler Carruth000d4282011-06-16 09:09:40 +00004713 // Never warn about void type pointers. This can be used to suppress
4714 // false positives.
4715 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004716 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004717
Chandler Carruth000d4282011-06-16 09:09:40 +00004718 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4719 // actually comparing the expressions for equality. Because computing the
4720 // expression IDs can be expensive, we only do this if the diagnostic is
4721 // enabled.
4722 if (SizeOfArg &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004723 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4724 SizeOfArg->getExprLoc())) {
Chandler Carruth000d4282011-06-16 09:09:40 +00004725 // We only compute IDs for expressions if the warning is enabled, and
4726 // cache the sizeof arg's ID.
4727 if (SizeOfArgID == llvm::FoldingSetNodeID())
4728 SizeOfArg->Profile(SizeOfArgID, Context, true);
4729 llvm::FoldingSetNodeID DestID;
4730 Dest->Profile(DestID, Context, true);
4731 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004732 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4733 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004734 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004735 StringRef ReadableName = FnName->getName();
4736
Chandler Carruth000d4282011-06-16 09:09:40 +00004737 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004738 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004739 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004740 if (!PointeeTy->isIncompleteType() &&
4741 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004742 ActionIdx = 2; // If the pointee's size is sizeof(char),
4743 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004744
4745 // If the function is defined as a builtin macro, do not show macro
4746 // expansion.
4747 SourceLocation SL = SizeOfArg->getExprLoc();
4748 SourceRange DSR = Dest->getSourceRange();
4749 SourceRange SSR = SizeOfArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004750 SourceManager &SM = getSourceManager();
Anna Zaks6fcb3722012-05-30 00:34:21 +00004751
4752 if (SM.isMacroArgExpansion(SL)) {
4753 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4754 SL = SM.getSpellingLoc(SL);
4755 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4756 SM.getSpellingLoc(DSR.getEnd()));
4757 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4758 SM.getSpellingLoc(SSR.getEnd()));
4759 }
4760
Anna Zaks90c78322012-05-30 23:14:52 +00004761 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004762 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004763 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004764 << PointeeTy
4765 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004766 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004767 << SSR);
4768 DiagRuntimeBehavior(SL, SizeOfArg,
4769 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4770 << ActionIdx
4771 << SSR);
4772
Chandler Carruth000d4282011-06-16 09:09:40 +00004773 break;
4774 }
4775 }
4776
4777 // Also check for cases where the sizeof argument is the exact same
4778 // type as the memory argument, and where it points to a user-defined
4779 // record type.
4780 if (SizeOfArgTy != QualType()) {
4781 if (PointeeTy->isRecordType() &&
4782 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4783 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4784 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4785 << FnName << SizeOfArgTy << ArgIdx
4786 << PointeeTy << Dest->getSourceRange()
4787 << LenExpr->getSourceRange());
4788 break;
4789 }
Nico Webere4a1c642011-06-14 16:14:58 +00004790 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004791 } else if (DestTy->isArrayType()) {
4792 PointeeTy = DestTy;
4793 }
Nico Webere4a1c642011-06-14 16:14:58 +00004794
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004795 if (PointeeTy == QualType())
4796 continue;
Anna Zaks0a151a12012-01-17 00:37:07 +00004797
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004798 // Always complain about dynamic classes.
4799 bool IsContained;
4800 if (const CXXRecordDecl *ContainedRD =
4801 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCallf85e1932011-06-15 23:02:42 +00004802
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004803 unsigned OperationType = 0;
4804 // "overwritten" if we're warning about the destination for any call
4805 // but memcmp; otherwise a verb appropriate to the call.
4806 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4807 if (BId == Builtin::BImemcpy)
4808 OperationType = 1;
4809 else if(BId == Builtin::BImemmove)
4810 OperationType = 2;
4811 else if (BId == Builtin::BImemcmp)
4812 OperationType = 3;
4813 }
4814
John McCallf85e1932011-06-15 23:02:42 +00004815 DiagRuntimeBehavior(
4816 Dest->getExprLoc(), Dest,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004817 PDiag(diag::warn_dyn_class_memaccess)
4818 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4819 << FnName << IsContained << ContainedRD << OperationType
4820 << Call->getCallee()->getSourceRange());
4821 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4822 BId != Builtin::BImemset)
4823 DiagRuntimeBehavior(
4824 Dest->getExprLoc(), Dest,
4825 PDiag(diag::warn_arc_object_memaccess)
4826 << ArgIdx << FnName << PointeeTy
4827 << Call->getCallee()->getSourceRange());
4828 else
4829 continue;
4830
4831 DiagRuntimeBehavior(
4832 Dest->getExprLoc(), Dest,
4833 PDiag(diag::note_bad_memaccess_silence)
4834 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4835 break;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004836 }
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07004837
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004838}
4839
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004840// A little helper routine: ignore addition and subtraction of integer literals.
4841// This intentionally does not ignore all integer constant expressions because
4842// we don't want to remove sizeof().
4843static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4844 Ex = Ex->IgnoreParenCasts();
4845
4846 for (;;) {
4847 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4848 if (!BO || !BO->isAdditiveOp())
4849 break;
4850
4851 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4852 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4853
4854 if (isa<IntegerLiteral>(RHS))
4855 Ex = LHS;
4856 else if (isa<IntegerLiteral>(LHS))
4857 Ex = RHS;
4858 else
4859 break;
4860 }
4861
4862 return Ex;
4863}
4864
Anna Zaks0f38ace2012-08-08 21:42:23 +00004865static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4866 ASTContext &Context) {
4867 // Only handle constant-sized or VLAs, but not flexible members.
4868 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4869 // Only issue the FIXIT for arrays of size > 1.
4870 if (CAT->getSize().getSExtValue() <= 1)
4871 return false;
4872 } else if (!Ty->isVariableArrayType()) {
4873 return false;
4874 }
4875 return true;
4876}
4877
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004878// Warn if the user has made the 'size' argument to strlcpy or strlcat
4879// be the size of the source, instead of the destination.
4880void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4881 IdentifierInfo *FnName) {
4882
4883 // Don't crash if the user has the wrong number of arguments
Stephen Hines176edba2014-12-01 14:53:08 -08004884 unsigned NumArgs = Call->getNumArgs();
4885 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004886 return;
4887
4888 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4889 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004890 const Expr *CompareWithSrc = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004891
4892 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4893 Call->getLocStart(), Call->getRParenLoc()))
4894 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004895
4896 // Look for 'strlcpy(dst, x, sizeof(x))'
4897 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4898 CompareWithSrc = Ex;
4899 else {
4900 // Look for 'strlcpy(dst, x, strlen(x))'
4901 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004902 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4903 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004904 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4905 }
4906 }
4907
4908 if (!CompareWithSrc)
4909 return;
4910
4911 // Determine if the argument to sizeof/strlen is equal to the source
4912 // argument. In principle there's all kinds of things you could do
4913 // here, for instance creating an == expression and evaluating it with
4914 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4915 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4916 if (!SrcArgDRE)
4917 return;
4918
4919 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4920 if (!CompareWithSrcDRE ||
4921 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4922 return;
4923
4924 const Expr *OriginalSizeArg = Call->getArg(2);
4925 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4926 << OriginalSizeArg->getSourceRange() << FnName;
4927
4928 // Output a FIXIT hint if the destination is an array (rather than a
4929 // pointer to an array). This could be enhanced to handle some
4930 // pointers if we know the actual size, like if DstArg is 'array+2'
4931 // we could say 'sizeof(array)-2'.
4932 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00004933 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00004934 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00004935
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004936 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00004937 llvm::raw_svector_ostream OS(sizeString);
4938 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004939 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00004940 OS << ")";
4941
4942 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4943 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4944 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004945}
4946
Anna Zaksc36bedc2012-02-01 19:08:57 +00004947/// Check if two expressions refer to the same declaration.
4948static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4949 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4950 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4951 return D1->getDecl() == D2->getDecl();
4952 return false;
4953}
4954
4955static const Expr *getStrlenExprArg(const Expr *E) {
4956 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4957 const FunctionDecl *FD = CE->getDirectCallee();
4958 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004959 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004960 return CE->getArg(0)->IgnoreParenCasts();
4961 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004962 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004963}
4964
4965// Warn on anti-patterns as the 'size' argument to strncat.
4966// The correct size argument should look like following:
4967// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4968void Sema::CheckStrncatArguments(const CallExpr *CE,
4969 IdentifierInfo *FnName) {
4970 // Don't crash if the user has the wrong number of arguments.
4971 if (CE->getNumArgs() < 3)
4972 return;
4973 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4974 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4975 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4976
Stephen Hines651f13c2014-04-23 16:59:28 -07004977 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4978 CE->getRParenLoc()))
4979 return;
4980
Anna Zaksc36bedc2012-02-01 19:08:57 +00004981 // Identify common expressions, which are wrongly used as the size argument
4982 // to strncat and may lead to buffer overflows.
4983 unsigned PatternType = 0;
4984 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4985 // - sizeof(dst)
4986 if (referToTheSameDecl(SizeOfArg, DstArg))
4987 PatternType = 1;
4988 // - sizeof(src)
4989 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4990 PatternType = 2;
4991 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4992 if (BE->getOpcode() == BO_Sub) {
4993 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4994 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4995 // - sizeof(dst) - strlen(dst)
4996 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4997 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4998 PatternType = 1;
4999 // - sizeof(src) - (anything)
5000 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5001 PatternType = 2;
5002 }
5003 }
5004
5005 if (PatternType == 0)
5006 return;
5007
Anna Zaksafdb0412012-02-03 01:27:37 +00005008 // Generate the diagnostic.
5009 SourceLocation SL = LenArg->getLocStart();
5010 SourceRange SR = LenArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005011 SourceManager &SM = getSourceManager();
Anna Zaksafdb0412012-02-03 01:27:37 +00005012
5013 // If the function is defined as a builtin macro, do not show macro expansion.
5014 if (SM.isMacroArgExpansion(SL)) {
5015 SL = SM.getSpellingLoc(SL);
5016 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5017 SM.getSpellingLoc(SR.getEnd()));
5018 }
5019
Anna Zaks0f38ace2012-08-08 21:42:23 +00005020 // Check if the destination is an array (rather than a pointer to an array).
5021 QualType DstTy = DstArg->getType();
5022 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5023 Context);
5024 if (!isKnownSizeArray) {
5025 if (PatternType == 1)
5026 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5027 else
5028 Diag(SL, diag::warn_strncat_src_size) << SR;
5029 return;
5030 }
5031
Anna Zaksc36bedc2012-02-01 19:08:57 +00005032 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00005033 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005034 else
Anna Zaksafdb0412012-02-03 01:27:37 +00005035 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005036
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00005037 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00005038 llvm::raw_svector_ostream OS(sizeString);
5039 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005040 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005041 OS << ") - ";
5042 OS << "strlen(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005043 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005044 OS << ") - 1";
5045
Anna Zaksafdb0412012-02-03 01:27:37 +00005046 Diag(SL, diag::note_strncat_wrong_size)
5047 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00005048}
5049
Ted Kremenek06de2762007-08-17 16:46:58 +00005050//===--- CHECK: Return Address of Stack Variable --------------------------===//
5051
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005052static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5053 Decl *ParentDecl);
5054static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5055 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005056
5057/// CheckReturnStackAddr - Check if a return statement returns the address
5058/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07005059static void
5060CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5061 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005062
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005063 Expr *stackE = nullptr;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005064 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005065
5066 // Perform checking for returned stack addresses, local blocks,
5067 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00005068 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07005069 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005070 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005071 } else if (lhsType->isReferenceType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005072 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005073 }
5074
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005075 if (!stackE)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005076 return; // Nothing suspicious was found.
5077
5078 SourceLocation diagLoc;
5079 SourceRange diagRange;
5080 if (refVars.empty()) {
5081 diagLoc = stackE->getLocStart();
5082 diagRange = stackE->getSourceRange();
5083 } else {
5084 // We followed through a reference variable. 'stackE' contains the
5085 // problematic expression but we will warn at the return statement pointing
5086 // at the reference variable. We will later display the "trail" of
5087 // reference variables using notes.
5088 diagLoc = refVars[0]->getLocStart();
5089 diagRange = refVars[0]->getSourceRange();
5090 }
5091
5092 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07005093 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005094 : diag::warn_ret_stack_addr)
5095 << DR->getDecl()->getDeclName() << diagRange;
5096 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07005097 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005098 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07005099 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005100 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07005101 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5102 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005103 << diagRange;
5104 }
5105
5106 // Display the "trail" of reference variables that we followed until we
5107 // found the problematic expression using notes.
5108 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5109 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5110 // If this var binds to another reference var, show the range of the next
5111 // var, otherwise the var binds to the problematic expression, in which case
5112 // show the range of the expression.
5113 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5114 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07005115 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5116 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00005117 }
5118}
5119
5120/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5121/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005122/// to a location on the stack, a local block, an address of a label, or a
5123/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00005124/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005125/// encounter a subexpression that (1) clearly does not lead to one of the
5126/// above problematic expressions (2) is something we cannot determine leads to
5127/// a problematic expression based on such local checking.
5128///
5129/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5130/// the expression that they point to. Such variables are added to the
5131/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00005132///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005133/// EvalAddr processes expressions that are pointers that are used as
5134/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005135/// At the base case of the recursion is a check for the above problematic
5136/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00005137///
5138/// This implementation handles:
5139///
5140/// * pointer-to-pointer casts
5141/// * implicit conversions from array references to pointers
5142/// * taking the address of fields
5143/// * arbitrary interplay between "&" and "*" operators
5144/// * pointer arithmetic from an address of a stack variable
5145/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005146static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5147 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005148 if (E->isTypeDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005149 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005150
Ted Kremenek06de2762007-08-17 16:46:58 +00005151 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00005152 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00005153 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005154 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005155 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Peter Collingbournef111d932011-04-15 00:35:48 +00005157 E = E->IgnoreParens();
5158
Ted Kremenek06de2762007-08-17 16:46:58 +00005159 // Our "symbolic interpreter" is just a dispatch off the currently
5160 // viewed AST node. We then recursively traverse the AST by calling
5161 // EvalAddr and EvalVal appropriately.
5162 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005163 case Stmt::DeclRefExprClass: {
5164 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5165
Stephen Hines651f13c2014-04-23 16:59:28 -07005166 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005167 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005168 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005169
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005170 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5171 // If this is a reference variable, follow through to the expression that
5172 // it points to.
5173 if (V->hasLocalStorage() &&
5174 V->getType()->isReferenceType() && V->hasInit()) {
5175 // Add the reference variable to the "trail".
5176 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005177 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005178 }
5179
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005180 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005181 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005182
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005183 case Stmt::UnaryOperatorClass: {
5184 // The only unary operator that make sense to handle here
5185 // is AddrOf. All others don't make sense as pointers.
5186 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005187
John McCall2de56d12010-08-25 11:45:40 +00005188 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005189 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005190 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005191 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005192 }
Mike Stump1eb44332009-09-09 15:08:12 +00005193
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005194 case Stmt::BinaryOperatorClass: {
5195 // Handle pointer arithmetic. All other binary operators are not valid
5196 // in this context.
5197 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00005198 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00005199
John McCall2de56d12010-08-25 11:45:40 +00005200 if (op != BO_Add && op != BO_Sub)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005201 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005202
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005203 Expr *Base = B->getLHS();
5204
5205 // Determine which argument is the real pointer base. It could be
5206 // the RHS argument instead of the LHS.
5207 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00005208
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005209 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005210 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005211 }
Steve Naroff61f40a22008-09-10 19:17:48 +00005212
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005213 // For conditional operators we need to see if either the LHS or RHS are
5214 // valid DeclRefExpr*s. If one of them is valid, we return it.
5215 case Stmt::ConditionalOperatorClass: {
5216 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005218 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005219 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5220 if (Expr *LHSExpr = C->getLHS()) {
5221 // In C++, we can have a throw-expression, which has 'void' type.
5222 if (!LHSExpr->getType()->isVoidType())
5223 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005224 return LHS;
5225 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005226
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005227 // In C++, we can have a throw-expression, which has 'void' type.
5228 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005229 return nullptr;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00005230
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005231 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005232 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005233
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005234 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00005235 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005236 return E; // local block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005237 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005238
5239 case Stmt::AddrLabelExprClass:
5240 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00005241
John McCall80ee6e82011-11-10 05:35:25 +00005242 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005243 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5244 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005245
Ted Kremenek54b52742008-08-07 00:49:01 +00005246 // For casts, we need to handle conversions from arrays to
5247 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00005248 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00005249 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005250 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00005251 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00005252 case Stmt::CXXStaticCastExprClass:
5253 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00005254 case Stmt::CXXConstCastExprClass:
5255 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005256 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5257 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8b9414e2012-02-23 23:04:32 +00005258 case CK_LValueToRValue:
5259 case CK_NoOp:
5260 case CK_BaseToDerived:
5261 case CK_DerivedToBase:
5262 case CK_UncheckedDerivedToBase:
5263 case CK_Dynamic:
5264 case CK_CPointerToObjCPointerCast:
5265 case CK_BlockPointerToObjCPointerCast:
5266 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005267 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005268
5269 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005270 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00005271
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005272 case CK_BitCast:
5273 if (SubExpr->getType()->isAnyPointerType() ||
5274 SubExpr->getType()->isBlockPointerType() ||
5275 SubExpr->getType()->isObjCQualifiedIdType())
5276 return EvalAddr(SubExpr, refVars, ParentDecl);
5277 else
5278 return nullptr;
5279
Eli Friedman8b9414e2012-02-23 23:04:32 +00005280 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005281 return nullptr;
Eli Friedman8b9414e2012-02-23 23:04:32 +00005282 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005283 }
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Douglas Gregor03e80032011-06-21 17:03:29 +00005285 case Stmt::MaterializeTemporaryExprClass:
5286 if (Expr *Result = EvalAddr(
5287 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005288 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005289 return Result;
5290
5291 return E;
5292
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005293 // Everything else: we simply don't reason about them.
5294 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005295 return nullptr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00005296 }
Ted Kremenek06de2762007-08-17 16:46:58 +00005297}
Mike Stump1eb44332009-09-09 15:08:12 +00005298
Ted Kremenek06de2762007-08-17 16:46:58 +00005299
5300/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5301/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005302static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5303 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005304do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00005305 // We should only be called for evaluating non-pointer expressions, or
5306 // expressions with a pointer type that are not used as references but instead
5307 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00005308
Ted Kremenek06de2762007-08-17 16:46:58 +00005309 // Our "symbolic interpreter" is just a dispatch off the currently
5310 // viewed AST node. We then recursively traverse the AST by calling
5311 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00005312
5313 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00005314 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005315 case Stmt::ImplicitCastExprClass: {
5316 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00005317 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00005318 E = IE->getSubExpr();
5319 continue;
5320 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005321 return nullptr;
Ted Kremenek68957a92010-08-04 20:01:07 +00005322 }
5323
John McCall80ee6e82011-11-10 05:35:25 +00005324 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005325 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00005326
Douglas Gregora2813ce2009-10-23 18:54:35 +00005327 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005328 // When we hit a DeclRefExpr we are looking at code that refers to a
5329 // variable's name. If it's not a reference variable we check if it has
5330 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00005331 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Stephen Hines651f13c2014-04-23 16:59:28 -07005333 // If we leave the immediate function, the lifetime isn't about to end.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005334 if (DR->refersToEnclosingVariableOrCapture())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005335 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07005336
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005337 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5338 // Check if it refers to itself, e.g. "int& i = i;".
5339 if (V == ParentDecl)
5340 return DR;
5341
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005342 if (V->hasLocalStorage()) {
5343 if (!V->getType()->isReferenceType())
5344 return DR;
5345
5346 // Reference variable, follow through to the expression that
5347 // it points to.
5348 if (V->hasInit()) {
5349 // Add the reference variable to the "trail".
5350 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005351 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005352 }
5353 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005354 }
Mike Stump1eb44332009-09-09 15:08:12 +00005355
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005356 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005357 }
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Ted Kremenek06de2762007-08-17 16:46:58 +00005359 case Stmt::UnaryOperatorClass: {
5360 // The only unary operator that make sense to handle here
5361 // is Deref. All others don't resolve to a "name." This includes
5362 // handling all sorts of rvalues passed to a unary operator.
5363 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005364
John McCall2de56d12010-08-25 11:45:40 +00005365 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005366 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005367
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005368 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005369 }
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Ted Kremenek06de2762007-08-17 16:46:58 +00005371 case Stmt::ArraySubscriptExprClass: {
5372 // Array subscripts are potential references to data on the stack. We
5373 // retrieve the DeclRefExpr* for the array variable if it indeed
5374 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005375 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005376 }
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Ted Kremenek06de2762007-08-17 16:46:58 +00005378 case Stmt::ConditionalOperatorClass: {
5379 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005380 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00005381 ConditionalOperator *C = cast<ConditionalOperator>(E);
5382
Anders Carlsson39073232007-11-30 19:04:31 +00005383 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07005384 if (Expr *LHSExpr = C->getLHS()) {
5385 // In C++, we can have a throw-expression, which has 'void' type.
5386 if (!LHSExpr->getType()->isVoidType())
5387 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5388 return LHS;
5389 }
5390
5391 // In C++, we can have a throw-expression, which has 'void' type.
5392 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005393 return nullptr;
Anders Carlsson39073232007-11-30 19:04:31 +00005394
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005395 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005396 }
Mike Stump1eb44332009-09-09 15:08:12 +00005397
Ted Kremenek06de2762007-08-17 16:46:58 +00005398 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00005399 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00005400 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Ted Kremenek06de2762007-08-17 16:46:58 +00005402 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00005403 if (M->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005404 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005405
5406 // Check whether the member type is itself a reference, in which case
5407 // we're not going to refer to the member, but to what the member refers to.
5408 if (M->getMemberDecl()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005409 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00005410
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005411 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00005412 }
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Douglas Gregor03e80032011-06-21 17:03:29 +00005414 case Stmt::MaterializeTemporaryExprClass:
5415 if (Expr *Result = EvalVal(
5416 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00005417 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00005418 return Result;
5419
5420 return E;
5421
Ted Kremenek06de2762007-08-17 16:46:58 +00005422 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00005423 // Check that we don't return or take the address of a reference to a
5424 // temporary. This is only useful in C++.
5425 if (!E->isTypeDependent() && E->isRValue())
5426 return E;
5427
5428 // Everything else: we simply don't reason about them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005429 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00005430 }
Ted Kremenek68957a92010-08-04 20:01:07 +00005431} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00005432}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005433
Stephen Hines651f13c2014-04-23 16:59:28 -07005434void
5435Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5436 SourceLocation ReturnLoc,
5437 bool isObjCMethod,
5438 const AttrVec *Attrs,
5439 const FunctionDecl *FD) {
5440 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5441
5442 // Check if the return value is null but should not be.
5443 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5444 CheckNonNullExpr(*this, RetValExp))
5445 Diag(ReturnLoc, diag::warn_null_ret)
5446 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5447
5448 // C++11 [basic.stc.dynamic.allocation]p4:
5449 // If an allocation function declared with a non-throwing
5450 // exception-specification fails to allocate storage, it shall return
5451 // a null pointer. Any other allocation function that fails to allocate
5452 // storage shall indicate failure only by throwing an exception [...]
5453 if (FD) {
5454 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5455 if (Op == OO_New || Op == OO_Array_New) {
5456 const FunctionProtoType *Proto
5457 = FD->getType()->castAs<FunctionProtoType>();
5458 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5459 CheckNonNullExpr(*this, RetValExp))
5460 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5461 << FD << getLangOpts().CPlusPlus11;
5462 }
5463 }
5464}
5465
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005466//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5467
5468/// Check for comparisons of floating point operands using != and ==.
5469/// Issue a warning if these are no self-comparisons, as they are not likely
5470/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00005471void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00005472 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5473 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005474
5475 // Special case: check for x == x (which is OK).
5476 // Do not emit warnings for such cases.
5477 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5478 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5479 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00005480 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005481
5482
Ted Kremenek1b500bb2007-11-29 00:59:04 +00005483 // Special case: check for comparisons against literals that can be exactly
5484 // represented by APFloat. In such cases, do not emit a warning. This
5485 // is a heuristic: often comparison against such literals are used to
5486 // detect if a value in a variable has not changed. This clearly can
5487 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00005488 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5489 if (FLL->isExact())
5490 return;
5491 } else
5492 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5493 if (FLR->isExact())
5494 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005495
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005496 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00005497 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005498 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005499 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005500
David Blaikie980343b2012-07-16 20:47:22 +00005501 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07005502 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00005503 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005504
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005505 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00005506 Diag(Loc, diag::warn_floatingpoint_eq)
5507 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00005508}
John McCallba26e582010-01-04 23:21:16 +00005509
John McCallf2370c92010-01-06 05:24:50 +00005510//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5511//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00005512
John McCallf2370c92010-01-06 05:24:50 +00005513namespace {
John McCallba26e582010-01-04 23:21:16 +00005514
John McCallf2370c92010-01-06 05:24:50 +00005515/// Structure recording the 'active' range of an integer-valued
5516/// expression.
5517struct IntRange {
5518 /// The number of bits active in the int.
5519 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00005520
John McCallf2370c92010-01-06 05:24:50 +00005521 /// True if the int is known not to have negative values.
5522 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00005523
John McCallf2370c92010-01-06 05:24:50 +00005524 IntRange(unsigned Width, bool NonNegative)
5525 : Width(Width), NonNegative(NonNegative)
5526 {}
John McCallba26e582010-01-04 23:21:16 +00005527
John McCall1844a6e2010-11-10 23:38:19 +00005528 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00005529 static IntRange forBoolType() {
5530 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00005531 }
5532
John McCall1844a6e2010-11-10 23:38:19 +00005533 /// Returns the range of an opaque value of the given integral type.
5534 static IntRange forValueOfType(ASTContext &C, QualType T) {
5535 return forValueOfCanonicalType(C,
5536 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00005537 }
5538
John McCall1844a6e2010-11-10 23:38:19 +00005539 /// Returns the range of an opaque value of a canonical integral type.
5540 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00005541 assert(T->isCanonicalUnqualified());
5542
5543 if (const VectorType *VT = dyn_cast<VectorType>(T))
5544 T = VT->getElementType().getTypePtr();
5545 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5546 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005547 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5548 T = AT->getValueType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00005549
David Majnemerf9eaf982013-06-07 22:07:20 +00005550 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00005551 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00005552 EnumDecl *Enum = ET->getDecl();
5553 if (!Enum->isCompleteDefinition())
5554 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00005555
David Majnemerf9eaf982013-06-07 22:07:20 +00005556 unsigned NumPositive = Enum->getNumPositiveBits();
5557 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00005558
David Majnemerf9eaf982013-06-07 22:07:20 +00005559 if (NumNegative == 0)
5560 return IntRange(NumPositive, true/*NonNegative*/);
5561 else
5562 return IntRange(std::max(NumPositive + 1, NumNegative),
5563 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00005564 }
John McCallf2370c92010-01-06 05:24:50 +00005565
5566 const BuiltinType *BT = cast<BuiltinType>(T);
5567 assert(BT->isInteger());
5568
5569 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5570 }
5571
John McCall1844a6e2010-11-10 23:38:19 +00005572 /// Returns the "target" range of a canonical integral type, i.e.
5573 /// the range of values expressible in the type.
5574 ///
5575 /// This matches forValueOfCanonicalType except that enums have the
5576 /// full range of their type, not the range of their enumerators.
5577 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5578 assert(T->isCanonicalUnqualified());
5579
5580 if (const VectorType *VT = dyn_cast<VectorType>(T))
5581 T = VT->getElementType().getTypePtr();
5582 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5583 T = CT->getElementType().getTypePtr();
Stephen Hines176edba2014-12-01 14:53:08 -08005584 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5585 T = AT->getValueType().getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005586 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00005587 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00005588
5589 const BuiltinType *BT = cast<BuiltinType>(T);
5590 assert(BT->isInteger());
5591
5592 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5593 }
5594
5595 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005596 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00005597 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00005598 L.NonNegative && R.NonNegative);
5599 }
5600
John McCall1844a6e2010-11-10 23:38:19 +00005601 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00005602 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00005603 return IntRange(std::min(L.Width, R.Width),
5604 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00005605 }
5606};
5607
Ted Kremenek0692a192012-01-31 05:37:37 +00005608static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5609 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005610 if (value.isSigned() && value.isNegative())
5611 return IntRange(value.getMinSignedBits(), false);
5612
5613 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00005614 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005615
5616 // isNonNegative() just checks the sign bit without considering
5617 // signedness.
5618 return IntRange(value.getActiveBits(), true);
5619}
5620
Ted Kremenek0692a192012-01-31 05:37:37 +00005621static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5622 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005623 if (result.isInt())
5624 return GetValueRange(C, result.getInt(), MaxWidth);
5625
5626 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00005627 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5628 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5629 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5630 R = IntRange::join(R, El);
5631 }
John McCallf2370c92010-01-06 05:24:50 +00005632 return R;
5633 }
5634
5635 if (result.isComplexInt()) {
5636 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5637 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5638 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00005639 }
5640
5641 // This can happen with lossless casts to intptr_t of "based" lvalues.
5642 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00005643 // FIXME: The only reason we need to pass the type in here is to get
5644 // the sign right on this one case. It would be nice if APValue
5645 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00005646 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005647 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00005648}
John McCallf2370c92010-01-06 05:24:50 +00005649
Eli Friedman09bddcf2013-07-08 20:20:06 +00005650static QualType GetExprType(Expr *E) {
5651 QualType Ty = E->getType();
5652 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5653 Ty = AtomicRHS->getValueType();
5654 return Ty;
5655}
5656
John McCallf2370c92010-01-06 05:24:50 +00005657/// Pseudo-evaluate the given integer expression, estimating the
5658/// range of values it might take.
5659///
5660/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00005661static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005662 E = E->IgnoreParens();
5663
5664 // Try a full evaluation first.
5665 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005666 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00005667 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005668
5669 // I think we only want to look through implicit casts here; if the
5670 // user has an explicit widening cast, we should treat the value as
5671 // being of the new, wider type.
5672 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00005673 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00005674 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5675
Eli Friedman09bddcf2013-07-08 20:20:06 +00005676 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00005677
John McCall2de56d12010-08-25 11:45:40 +00005678 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00005679
John McCallf2370c92010-01-06 05:24:50 +00005680 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00005681 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00005682 return OutputTypeRange;
5683
5684 IntRange SubRange
5685 = GetExprRange(C, CE->getSubExpr(),
5686 std::min(MaxWidth, OutputTypeRange.Width));
5687
5688 // Bail out if the subexpr's range is as wide as the cast type.
5689 if (SubRange.Width >= OutputTypeRange.Width)
5690 return OutputTypeRange;
5691
5692 // Otherwise, we take the smaller width, and we're non-negative if
5693 // either the output type or the subexpr is.
5694 return IntRange(SubRange.Width,
5695 SubRange.NonNegative || OutputTypeRange.NonNegative);
5696 }
5697
5698 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5699 // If we can fold the condition, just take that operand.
5700 bool CondResult;
5701 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5702 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5703 : CO->getFalseExpr(),
5704 MaxWidth);
5705
5706 // Otherwise, conservatively merge.
5707 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5708 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5709 return IntRange::join(L, R);
5710 }
5711
5712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5713 switch (BO->getOpcode()) {
5714
5715 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005716 case BO_LAnd:
5717 case BO_LOr:
5718 case BO_LT:
5719 case BO_GT:
5720 case BO_LE:
5721 case BO_GE:
5722 case BO_EQ:
5723 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005724 return IntRange::forBoolType();
5725
John McCall862ff872011-07-13 06:35:24 +00005726 // The type of the assignments is the type of the LHS, so the RHS
5727 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005728 case BO_MulAssign:
5729 case BO_DivAssign:
5730 case BO_RemAssign:
5731 case BO_AddAssign:
5732 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005733 case BO_XorAssign:
5734 case BO_OrAssign:
5735 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005736 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005737
John McCall862ff872011-07-13 06:35:24 +00005738 // Simple assignments just pass through the RHS, which will have
5739 // been coerced to the LHS type.
5740 case BO_Assign:
5741 // TODO: bitfields?
5742 return GetExprRange(C, BO->getRHS(), MaxWidth);
5743
John McCallf2370c92010-01-06 05:24:50 +00005744 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005745 case BO_PtrMemD:
5746 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005747 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005748
John McCall60fad452010-01-06 22:07:33 +00005749 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005750 case BO_And:
5751 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005752 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5753 GetExprRange(C, BO->getRHS(), MaxWidth));
5754
John McCallf2370c92010-01-06 05:24:50 +00005755 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005756 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005757 // ...except that we want to treat '1 << (blah)' as logically
5758 // positive. It's an important idiom.
5759 if (IntegerLiteral *I
5760 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5761 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005762 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005763 return IntRange(R.Width, /*NonNegative*/ true);
5764 }
5765 }
5766 // fallthrough
5767
John McCall2de56d12010-08-25 11:45:40 +00005768 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005769 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005770
John McCall60fad452010-01-06 22:07:33 +00005771 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005772 case BO_Shr:
5773 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005774 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5775
5776 // If the shift amount is a positive constant, drop the width by
5777 // that much.
5778 llvm::APSInt shift;
5779 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5780 shift.isNonNegative()) {
5781 unsigned zext = shift.getZExtValue();
5782 if (zext >= L.Width)
5783 L.Width = (L.NonNegative ? 0 : 1);
5784 else
5785 L.Width -= zext;
5786 }
5787
5788 return L;
5789 }
5790
5791 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005792 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005793 return GetExprRange(C, BO->getRHS(), MaxWidth);
5794
John McCall60fad452010-01-06 22:07:33 +00005795 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005796 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005797 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005798 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005799 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005800
John McCall00fe7612011-07-14 22:39:48 +00005801 // The width of a division result is mostly determined by the size
5802 // of the LHS.
5803 case BO_Div: {
5804 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005805 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005806 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5807
5808 // If the divisor is constant, use that.
5809 llvm::APSInt divisor;
5810 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5811 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5812 if (log2 >= L.Width)
5813 L.Width = (L.NonNegative ? 0 : 1);
5814 else
5815 L.Width = std::min(L.Width - log2, MaxWidth);
5816 return L;
5817 }
5818
5819 // Otherwise, just use the LHS's width.
5820 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5821 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5822 }
5823
5824 // The result of a remainder can't be larger than the result of
5825 // either side.
5826 case BO_Rem: {
5827 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005828 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005829 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5830 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5831
5832 IntRange meet = IntRange::meet(L, R);
5833 meet.Width = std::min(meet.Width, MaxWidth);
5834 return meet;
5835 }
5836
5837 // The default behavior is okay for these.
5838 case BO_Mul:
5839 case BO_Add:
5840 case BO_Xor:
5841 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005842 break;
5843 }
5844
John McCall00fe7612011-07-14 22:39:48 +00005845 // The default case is to treat the operation as if it were closed
5846 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005847 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5848 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5849 return IntRange::join(L, R);
5850 }
5851
5852 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5853 switch (UO->getOpcode()) {
5854 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005855 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005856 return IntRange::forBoolType();
5857
5858 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005859 case UO_Deref:
5860 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005861 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005862
5863 default:
5864 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5865 }
5866 }
5867
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005868 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5869 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5870
John McCall993f43f2013-05-06 21:39:12 +00005871 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005872 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005873 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005874
Eli Friedman09bddcf2013-07-08 20:20:06 +00005875 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005876}
John McCall51313c32010-01-04 23:31:57 +00005877
Ted Kremenek0692a192012-01-31 05:37:37 +00005878static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005879 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005880}
5881
John McCall51313c32010-01-04 23:31:57 +00005882/// Checks whether the given value, which currently has the given
5883/// source semantics, has the same value when coerced through the
5884/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005885static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5886 const llvm::fltSemantics &Src,
5887 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005888 llvm::APFloat truncated = value;
5889
5890 bool ignored;
5891 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5892 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5893
5894 return truncated.bitwiseIsEqual(value);
5895}
5896
5897/// Checks whether the given value, which currently has the given
5898/// source semantics, has the same value when coerced through the
5899/// target semantics.
5900///
5901/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005902static bool IsSameFloatAfterCast(const APValue &value,
5903 const llvm::fltSemantics &Src,
5904 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005905 if (value.isFloat())
5906 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5907
5908 if (value.isVector()) {
5909 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5910 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5911 return false;
5912 return true;
5913 }
5914
5915 assert(value.isComplexFloat());
5916 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5917 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5918}
5919
Ted Kremenek0692a192012-01-31 05:37:37 +00005920static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005921
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005922static bool IsZero(Sema &S, Expr *E) {
5923 // Suppress cases where we are comparing against an enum constant.
5924 if (const DeclRefExpr *DR =
5925 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5926 if (isa<EnumConstantDecl>(DR->getDecl()))
5927 return false;
5928
5929 // Suppress cases where the '0' value is expanded from a macro.
5930 if (E->getLocStart().isMacroID())
5931 return false;
5932
John McCall323ed742010-05-06 08:58:33 +00005933 llvm::APSInt Value;
5934 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5935}
5936
John McCall372e1032010-10-06 00:25:24 +00005937static bool HasEnumType(Expr *E) {
5938 // Strip off implicit integral promotions.
5939 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005940 if (ICE->getCastKind() != CK_IntegralCast &&
5941 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00005942 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005943 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00005944 }
5945
5946 return E->getType()->isEnumeralType();
5947}
5948
Ted Kremenek0692a192012-01-31 05:37:37 +00005949static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00005950 // Disable warning in template instantiations.
5951 if (!S.ActiveTemplateInstantiations.empty())
5952 return;
5953
John McCall2de56d12010-08-25 11:45:40 +00005954 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00005955 if (E->isValueDependent())
5956 return;
5957
John McCall2de56d12010-08-25 11:45:40 +00005958 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005959 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005960 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005961 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005962 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005963 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005964 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005965 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005966 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005967 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005968 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005969 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005970 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005971 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005972 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005973 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5974 }
5975}
5976
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005977static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005978 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005979 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005980 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00005981 // Disable warning in template instantiations.
5982 if (!S.ActiveTemplateInstantiations.empty())
5983 return;
5984
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005985 // TODO: Investigate using GetExprRange() to get tighter bounds
5986 // on the bit ranges.
5987 QualType OtherT = Other->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08005988 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5989 OtherT = AT->getValueType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005990 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5991 unsigned OtherWidth = OtherRange.Width;
5992
5993 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5994
Richard Trieu526e6272012-11-14 22:50:24 +00005995 // 0 values are handled later by CheckTrivialUnsignedComparison().
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005996 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu526e6272012-11-14 22:50:24 +00005997 return;
5998
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005999 BinaryOperatorKind op = E->getOpcode();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006000 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00006001
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006002 // Used for diagnostic printout.
6003 enum {
6004 LiteralConstant = 0,
6005 CXXBoolLiteralTrue,
6006 CXXBoolLiteralFalse
6007 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00006008
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006009 if (!OtherIsBooleanType) {
6010 QualType ConstantT = Constant->getType();
6011 QualType CommonT = E->getLHS()->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00006012
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006013 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6014 return;
6015 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6016 "comparison with non-integer type");
6017
6018 bool ConstantSigned = ConstantT->isSignedIntegerType();
6019 bool CommonSigned = CommonT->isSignedIntegerType();
6020
6021 bool EqualityOnly = false;
6022
6023 if (CommonSigned) {
6024 // The common type is signed, therefore no signed to unsigned conversion.
6025 if (!OtherRange.NonNegative) {
6026 // Check that the constant is representable in type OtherT.
6027 if (ConstantSigned) {
6028 if (OtherWidth >= Value.getMinSignedBits())
6029 return;
6030 } else { // !ConstantSigned
6031 if (OtherWidth >= Value.getActiveBits() + 1)
6032 return;
6033 }
6034 } else { // !OtherSigned
6035 // Check that the constant is representable in type OtherT.
6036 // Negative values are out of range.
6037 if (ConstantSigned) {
6038 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6039 return;
6040 } else { // !ConstantSigned
6041 if (OtherWidth >= Value.getActiveBits())
6042 return;
6043 }
Richard Trieu526e6272012-11-14 22:50:24 +00006044 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006045 } else { // !CommonSigned
6046 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00006047 if (OtherWidth >= Value.getActiveBits())
6048 return;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006049 } else { // OtherSigned
6050 assert(!ConstantSigned &&
6051 "Two signed types converted to unsigned types.");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006052 // Check to see if the constant is representable in OtherT.
6053 if (OtherWidth > Value.getActiveBits())
6054 return;
6055 // Check to see if the constant is equivalent to a negative value
6056 // cast to CommonT.
6057 if (S.Context.getIntWidth(ConstantT) ==
6058 S.Context.getIntWidth(CommonT) &&
6059 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6060 return;
6061 // The constant value rests between values that OtherT can represent
6062 // after conversion. Relational comparison still works, but equality
6063 // comparisons will be tautological.
6064 EqualityOnly = true;
Richard Trieu526e6272012-11-14 22:50:24 +00006065 }
6066 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006067
6068 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6069
6070 if (op == BO_EQ || op == BO_NE) {
6071 IsTrue = op == BO_NE;
6072 } else if (EqualityOnly) {
6073 return;
6074 } else if (RhsConstant) {
6075 if (op == BO_GT || op == BO_GE)
6076 IsTrue = !PositiveConstant;
6077 else // op == BO_LT || op == BO_LE
6078 IsTrue = PositiveConstant;
6079 } else {
6080 if (op == BO_LT || op == BO_LE)
6081 IsTrue = !PositiveConstant;
6082 else // op == BO_GT || op == BO_GE
6083 IsTrue = PositiveConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00006084 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006085 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006086 // Other isKnownToHaveBooleanValue
6087 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6088 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6089 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6090
6091 static const struct LinkedConditions {
6092 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6093 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6094 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6095 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6096 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6097 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6098
6099 } TruthTable = {
6100 // Constant on LHS. | Constant on RHS. |
6101 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6102 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6103 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6104 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6105 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6106 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6107 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6108 };
6109
6110 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6111
6112 enum ConstantValue ConstVal = Zero;
6113 if (Value.isUnsigned() || Value.isNonNegative()) {
6114 if (Value == 0) {
6115 LiteralOrBoolConstant =
6116 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6117 ConstVal = Zero;
6118 } else if (Value == 1) {
6119 LiteralOrBoolConstant =
6120 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6121 ConstVal = One;
6122 } else {
6123 LiteralOrBoolConstant = LiteralConstant;
6124 ConstVal = GT_One;
6125 }
6126 } else {
6127 ConstVal = LT_Zero;
6128 }
6129
6130 CompareBoolWithConstantResult CmpRes;
6131
6132 switch (op) {
6133 case BO_LT:
6134 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6135 break;
6136 case BO_GT:
6137 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6138 break;
6139 case BO_LE:
6140 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6141 break;
6142 case BO_GE:
6143 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6144 break;
6145 case BO_EQ:
6146 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6147 break;
6148 case BO_NE:
6149 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6150 break;
6151 default:
6152 CmpRes = Unkwn;
6153 break;
6154 }
6155
6156 if (CmpRes == AFals) {
6157 IsTrue = false;
6158 } else if (CmpRes == ATrue) {
6159 IsTrue = true;
6160 } else {
6161 return;
6162 }
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006163 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006164
6165 // If this is a comparison to an enum constant, include that
6166 // constant in the diagnostic.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006167 const EnumConstantDecl *ED = nullptr;
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006168 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6169 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6170
6171 SmallString<64> PrettySourceValue;
6172 llvm::raw_svector_ostream OS(PrettySourceValue);
6173 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00006174 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00006175 else
6176 OS << Value;
6177
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006178 S.DiagRuntimeBehavior(
6179 E->getOperatorLoc(), E,
6180 S.PDiag(diag::warn_out_of_range_compare)
6181 << OS.str() << LiteralOrBoolConstant
6182 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6183 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006184}
6185
John McCall323ed742010-05-06 08:58:33 +00006186/// Analyze the operands of the given comparison. Implements the
6187/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00006188static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00006189 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6190 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00006191}
John McCall51313c32010-01-04 23:31:57 +00006192
John McCallba26e582010-01-04 23:21:16 +00006193/// \brief Implements -Wsign-compare.
6194///
Richard Trieudd225092011-09-15 21:56:47 +00006195/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00006196static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00006197 // The type the comparison is being performed in.
6198 QualType T = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08006199
6200 // Only analyze comparison operators where both sides have been converted to
6201 // the same type.
6202 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6203 return AnalyzeImpConvsInComparison(S, E);
6204
6205 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00006206 if (E->isValueDependent())
6207 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006208
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006209 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6210 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006211
6212 bool IsComparisonConstant = false;
6213
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006214 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006215 // of 'true' or 'false'.
6216 if (T->isIntegralType(S.Context)) {
6217 llvm::APSInt RHSValue;
6218 bool IsRHSIntegralLiteral =
6219 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6220 llvm::APSInt LHSValue;
6221 bool IsLHSIntegralLiteral =
6222 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6223 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6224 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6225 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6226 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6227 else
6228 IsComparisonConstant =
6229 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00006230 } else if (!T->hasUnsignedIntegerRepresentation())
6231 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006232
John McCall323ed742010-05-06 08:58:33 +00006233 // We don't do anything special if this isn't an unsigned integral
6234 // comparison: we're only interested in integral comparisons, and
6235 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00006236 //
6237 // We also don't care about value-dependent expressions or expressions
6238 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006239 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00006240 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00006241
John McCall323ed742010-05-06 08:58:33 +00006242 // Check to see if one of the (unmodified) operands is of different
6243 // signedness.
6244 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00006245 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6246 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00006247 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00006248 signedOperand = LHS;
6249 unsignedOperand = RHS;
6250 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6251 signedOperand = RHS;
6252 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00006253 } else {
John McCall323ed742010-05-06 08:58:33 +00006254 CheckTrivialUnsignedComparison(S, E);
6255 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006256 }
6257
John McCall323ed742010-05-06 08:58:33 +00006258 // Otherwise, calculate the effective range of the signed operand.
6259 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00006260
John McCall323ed742010-05-06 08:58:33 +00006261 // Go ahead and analyze implicit conversions in the operands. Note
6262 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00006263 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6264 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00006265
John McCall323ed742010-05-06 08:58:33 +00006266 // If the signed range is non-negative, -Wsign-compare won't fire,
6267 // but we should still check for comparisons which are always true
6268 // or false.
6269 if (signedRange.NonNegative)
6270 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00006271
6272 // For (in)equality comparisons, if the unsigned operand is a
6273 // constant which cannot collide with a overflowed signed operand,
6274 // then reinterpreting the signed operand as unsigned will not
6275 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00006276 if (E->isEqualityOp()) {
6277 unsigned comparisonWidth = S.Context.getIntWidth(T);
6278 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00006279
John McCall323ed742010-05-06 08:58:33 +00006280 // We should never be unable to prove that the unsigned operand is
6281 // non-negative.
6282 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6283
6284 if (unsignedRange.Width < comparisonWidth)
6285 return;
6286 }
6287
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00006288 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6289 S.PDiag(diag::warn_mixed_sign_comparison)
6290 << LHS->getType() << RHS->getType()
6291 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00006292}
6293
John McCall15d7d122010-11-11 03:21:53 +00006294/// Analyzes an attempt to assign the given value to a bitfield.
6295///
6296/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00006297static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6298 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00006299 assert(Bitfield->isBitField());
6300 if (Bitfield->isInvalidDecl())
6301 return false;
6302
John McCall91b60142010-11-11 05:33:51 +00006303 // White-list bool bitfields.
6304 if (Bitfield->getType()->isBooleanType())
6305 return false;
6306
Douglas Gregor46ff3032011-02-04 13:09:01 +00006307 // Ignore value- or type-dependent expressions.
6308 if (Bitfield->getBitWidth()->isValueDependent() ||
6309 Bitfield->getBitWidth()->isTypeDependent() ||
6310 Init->isValueDependent() ||
6311 Init->isTypeDependent())
6312 return false;
6313
John McCall15d7d122010-11-11 03:21:53 +00006314 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6315
Richard Smith80d4b552011-12-28 19:48:30 +00006316 llvm::APSInt Value;
6317 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00006318 return false;
6319
John McCall15d7d122010-11-11 03:21:53 +00006320 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006321 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00006322
6323 if (OriginalWidth <= FieldWidth)
6324 return false;
6325
Eli Friedman3a643af2012-01-26 23:11:39 +00006326 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006327 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00006328 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00006329
Eli Friedman3a643af2012-01-26 23:11:39 +00006330 // Check whether the stored value is equal to the original value.
6331 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00006332 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00006333 return false;
6334
Eli Friedman3a643af2012-01-26 23:11:39 +00006335 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00006336 // therefore don't strictly fit into a signed bitfield of width 1.
6337 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00006338 return false;
6339
John McCall15d7d122010-11-11 03:21:53 +00006340 std::string PrettyValue = Value.toString(10);
6341 std::string PrettyTrunc = TruncatedValue.toString(10);
6342
6343 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6344 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6345 << Init->getSourceRange();
6346
6347 return true;
6348}
6349
John McCallbeb22aa2010-11-09 23:24:47 +00006350/// Analyze the given simple or compound assignment for warning-worthy
6351/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00006352static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00006353 // Just recurse on the LHS.
6354 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6355
6356 // We want to recurse on the RHS as normal unless we're assigning to
6357 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00006358 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006359 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00006360 E->getOperatorLoc())) {
6361 // Recurse, ignoring any implicit conversions on the RHS.
6362 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6363 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00006364 }
6365 }
6366
6367 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6368}
6369
John McCall51313c32010-01-04 23:31:57 +00006370/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006371static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006372 SourceLocation CContext, unsigned diag,
6373 bool pruneControlFlow = false) {
6374 if (pruneControlFlow) {
6375 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6376 S.PDiag(diag)
6377 << SourceType << T << E->getSourceRange()
6378 << SourceRange(CContext));
6379 return;
6380 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006381 S.Diag(E->getExprLoc(), diag)
6382 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6383}
6384
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006385/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00006386static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00006387 SourceLocation CContext, unsigned diag,
6388 bool pruneControlFlow = false) {
6389 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00006390}
6391
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006392/// Diagnose an implicit cast from a literal expression. Does not warn when the
6393/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006394void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6395 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006396 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00006397 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006398 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00006399 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6400 T->hasUnsignedIntegerRepresentation());
6401 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00006402 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006403 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00006404 return;
6405
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006406 // FIXME: Force the precision of the source value down so we don't print
6407 // digits which are usually useless (we don't really care here if we
6408 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6409 // would automatically print the shortest representation, but it's a bit
6410 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00006411 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00006412 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6413 precision = (precision * 59 + 195) / 196;
6414 Value.toString(PrettySourceValue, precision);
6415
David Blaikiede7e7b82012-05-15 17:18:27 +00006416 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00006417 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6418 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6419 else
David Blaikiede7e7b82012-05-15 17:18:27 +00006420 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00006421
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00006422 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00006423 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6424 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00006425}
6426
John McCall091f23f2010-11-09 22:22:12 +00006427std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6428 if (!Range.Width) return "0";
6429
6430 llvm::APSInt ValueInRange = Value;
6431 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00006432 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00006433 return ValueInRange.toString(10);
6434}
6435
Hans Wennborg88617a22012-08-28 15:44:30 +00006436static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6437 if (!isa<ImplicitCastExpr>(Ex))
6438 return false;
6439
6440 Expr *InnerE = Ex->IgnoreParenImpCasts();
6441 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6442 const Type *Source =
6443 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6444 if (Target->isDependentType())
6445 return false;
6446
6447 const BuiltinType *FloatCandidateBT =
6448 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6449 const Type *BoolCandidateType = ToBool ? Target : Source;
6450
6451 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6452 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6453}
6454
6455void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6456 SourceLocation CC) {
6457 unsigned NumArgs = TheCall->getNumArgs();
6458 for (unsigned i = 0; i < NumArgs; ++i) {
6459 Expr *CurrA = TheCall->getArg(i);
6460 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6461 continue;
6462
6463 bool IsSwapped = ((i > 0) &&
6464 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6465 IsSwapped |= ((i < (NumArgs - 1)) &&
6466 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6467 if (IsSwapped) {
6468 // Warn on this floating-point to bool conversion.
6469 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6470 CurrA->getType(), CC,
6471 diag::warn_impcast_floating_point_to_bool);
6472 }
6473 }
6474}
6475
Stephen Hines176edba2014-12-01 14:53:08 -08006476static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6477 SourceLocation CC) {
6478 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6479 E->getExprLoc()))
6480 return;
6481
6482 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6483 const Expr::NullPointerConstantKind NullKind =
6484 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6485 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6486 return;
6487
6488 // Return if target type is a safe conversion.
6489 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6490 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6491 return;
6492
6493 SourceLocation Loc = E->getSourceRange().getBegin();
6494
6495 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6496 if (NullKind == Expr::NPCK_GNUNull) {
6497 if (Loc.isMacroID())
6498 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6499 }
6500
6501 // Only warn if the null and context location are in the same macro expansion.
6502 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6503 return;
6504
6505 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6506 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6507 << FixItHint::CreateReplacement(Loc,
6508 S.getFixItZeroLiteralForType(T, Loc));
6509}
6510
John McCall323ed742010-05-06 08:58:33 +00006511void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006512 SourceLocation CC, bool *ICContext = nullptr) {
John McCall323ed742010-05-06 08:58:33 +00006513 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00006514
John McCall323ed742010-05-06 08:58:33 +00006515 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6516 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6517 if (Source == Target) return;
6518 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00006519
Chandler Carruth108f7562011-07-26 05:40:03 +00006520 // If the conversion context location is invalid don't complain. We also
6521 // don't want to emit a warning if the issue occurs from the expansion of
6522 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6523 // delay this check as long as possible. Once we detect we are in that
6524 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00006525 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00006526 return;
6527
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006528 // Diagnose implicit casts to bool.
6529 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6530 if (isa<StringLiteral>(E))
6531 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07006532 // and expressions, for instance, assert(0 && "error here"), are
6533 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006534 return DiagnoseImpCast(S, E, T, CC,
6535 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07006536 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6537 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6538 // This covers the literal expressions that evaluate to Objective-C
6539 // objects.
6540 return DiagnoseImpCast(S, E, T, CC,
6541 diag::warn_impcast_objective_c_literal_to_bool);
6542 }
6543 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6544 // Warn on pointer to bool conversion that is always true.
6545 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6546 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00006547 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006548 }
John McCall51313c32010-01-04 23:31:57 +00006549
6550 // Strip vector types.
6551 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006552 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006553 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006554 return;
John McCallb4eb64d2010-10-08 02:01:28 +00006555 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006556 }
Chris Lattnerb792b302011-06-14 04:51:15 +00006557
6558 // If the vector cast is cast between two vectors of the same size, it is
6559 // a bitcast, not a conversion.
6560 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6561 return;
John McCall51313c32010-01-04 23:31:57 +00006562
6563 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6564 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6565 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006566 if (auto VecTy = dyn_cast<VectorType>(Target))
6567 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00006568
6569 // Strip complex types.
6570 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006571 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006572 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006573 return;
6574
John McCallb4eb64d2010-10-08 02:01:28 +00006575 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006576 }
John McCall51313c32010-01-04 23:31:57 +00006577
6578 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6579 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6580 }
6581
6582 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6583 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6584
6585 // If the source is floating point...
6586 if (SourceBT && SourceBT->isFloatingPoint()) {
6587 // ...and the target is floating point...
6588 if (TargetBT && TargetBT->isFloatingPoint()) {
6589 // ...then warn if we're dropping FP rank.
6590
6591 // Builtin FP kinds are ordered by increasing FP rank.
6592 if (SourceBT->getKind() > TargetBT->getKind()) {
6593 // Don't warn about float constants that are precisely
6594 // representable in the target type.
6595 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00006596 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00006597 // Value might be a float, a float vector, or a float complex.
6598 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00006599 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6600 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00006601 return;
6602 }
6603
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006604 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006605 return;
6606
John McCallb4eb64d2010-10-08 02:01:28 +00006607 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00006608 }
6609 return;
6610 }
6611
Ted Kremenekef9ff882011-03-10 20:03:42 +00006612 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00006613 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006614 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006615 return;
6616
Chandler Carrutha5b93322011-02-17 11:05:49 +00006617 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00006618 // We also want to warn on, e.g., "int i = -1.234"
6619 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6620 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6621 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6622
Chandler Carruthf65076e2011-04-10 08:36:24 +00006623 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6624 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00006625 } else {
6626 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6627 }
6628 }
John McCall51313c32010-01-04 23:31:57 +00006629
Hans Wennborg88617a22012-08-28 15:44:30 +00006630 // If the target is bool, warn if expr is a function or method call.
6631 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6632 isa<CallExpr>(E)) {
6633 // Check last argument of function call to see if it is an
6634 // implicit cast from a type matching the type the result
6635 // is being cast to.
6636 CallExpr *CEx = cast<CallExpr>(E);
6637 unsigned NumArgs = CEx->getNumArgs();
6638 if (NumArgs > 0) {
6639 Expr *LastA = CEx->getArg(NumArgs - 1);
6640 Expr *InnerE = LastA->IgnoreParenImpCasts();
6641 const Type *InnerType =
6642 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6643 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6644 // Warn on this floating-point to bool conversion
6645 DiagnoseImpCast(S, E, T, CC,
6646 diag::warn_impcast_floating_point_to_bool);
6647 }
6648 }
6649 }
John McCall51313c32010-01-04 23:31:57 +00006650 return;
6651 }
6652
Stephen Hines176edba2014-12-01 14:53:08 -08006653 DiagnoseNullConversion(S, E, T, CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00006654
David Blaikieb26331b2012-06-19 21:19:06 +00006655 if (!Source->isIntegerType() || !Target->isIntegerType())
6656 return;
6657
David Blaikiebe0ee872012-05-15 16:56:36 +00006658 // TODO: remove this early return once the false positives for constant->bool
6659 // in templates, macros, etc, are reduced or removed.
6660 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6661 return;
6662
John McCall323ed742010-05-06 08:58:33 +00006663 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00006664 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00006665
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006666 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00006667 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006668 // TODO: this should happen for bitfield stores, too.
6669 llvm::APSInt Value(32);
6670 if (E->isIntegerConstantExpr(Value, S.Context)) {
6671 if (S.SourceMgr.isInSystemMacro(CC))
6672 return;
6673
John McCall091f23f2010-11-09 22:22:12 +00006674 std::string PrettySourceValue = Value.toString(10);
6675 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006676
Ted Kremenek5e745da2011-10-22 02:37:33 +00006677 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6678 S.PDiag(diag::warn_impcast_integer_precision_constant)
6679 << PrettySourceValue << PrettyTargetValue
6680 << E->getType() << T << E->getSourceRange()
6681 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00006682 return;
6683 }
6684
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006685 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6686 if (S.SourceMgr.isInSystemMacro(CC))
6687 return;
6688
David Blaikie37050842012-04-12 22:40:54 +00006689 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00006690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6691 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00006692 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00006693 }
6694
6695 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6696 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6697 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00006698
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006699 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006700 return;
6701
John McCall323ed742010-05-06 08:58:33 +00006702 unsigned DiagID = diag::warn_impcast_integer_sign;
6703
6704 // Traditionally, gcc has warned about this under -Wsign-compare.
6705 // We also want to warn about it in -Wconversion.
6706 // So if -Wconversion is off, use a completely identical diagnostic
6707 // in the sign-compare group.
6708 // The conditional-checking code will
6709 if (ICContext) {
6710 DiagID = diag::warn_impcast_integer_sign_conditional;
6711 *ICContext = true;
6712 }
6713
John McCallb4eb64d2010-10-08 02:01:28 +00006714 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00006715 }
6716
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006717 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006718 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6719 // type, to give us better diagnostics.
6720 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00006721 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006722 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6723 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6724 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6725 SourceType = S.Context.getTypeDeclType(Enum);
6726 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6727 }
6728 }
6729
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006730 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6731 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00006732 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6733 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00006734 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006735 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006736 return;
6737
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006738 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006739 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006740 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006741
John McCall51313c32010-01-04 23:31:57 +00006742 return;
6743}
6744
David Blaikie9fb1ac52012-05-15 21:57:38 +00006745void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6746 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00006747
6748void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00006749 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00006750 E = E->IgnoreParenImpCasts();
6751
6752 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00006753 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00006754
John McCallb4eb64d2010-10-08 02:01:28 +00006755 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006756 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006757 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00006758 return;
6759}
6760
David Blaikie9fb1ac52012-05-15 21:57:38 +00006761void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6762 SourceLocation CC, QualType T) {
Stephen Hines176edba2014-12-01 14:53:08 -08006763 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCall323ed742010-05-06 08:58:33 +00006764
6765 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00006766 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6767 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006768
6769 // If -Wconversion would have warned about either of the candidates
6770 // for a signedness conversion to the context type...
6771 if (!Suspicious) return;
6772
6773 // ...but it's currently ignored...
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006774 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00006775 return;
6776
John McCall323ed742010-05-06 08:58:33 +00006777 // ...then check whether it would have warned about either of the
6778 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006779 if (E->getType() == T) return;
6780
6781 Suspicious = false;
6782 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6783 E->getType(), CC, &Suspicious);
6784 if (!Suspicious)
6785 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006786 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006787}
6788
Stephen Hines176edba2014-12-01 14:53:08 -08006789/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6790/// Input argument E is a logical expression.
6791static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6792 if (S.getLangOpts().Bool)
6793 return;
6794 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6795}
6796
John McCall323ed742010-05-06 08:58:33 +00006797/// AnalyzeImplicitConversions - Find and report any interesting
6798/// implicit conversions in the given expression. There are a couple
6799/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006800void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006801 QualType T = OrigE->getType();
6802 Expr *E = OrigE->IgnoreParenImpCasts();
6803
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006804 if (E->isTypeDependent() || E->isValueDependent())
6805 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006806
John McCall323ed742010-05-06 08:58:33 +00006807 // For conditional operators, we analyze the arguments as if they
6808 // were being fed directly into the output.
6809 if (isa<ConditionalOperator>(E)) {
6810 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006811 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006812 return;
6813 }
6814
Hans Wennborg88617a22012-08-28 15:44:30 +00006815 // Check implicit argument conversions for function calls.
6816 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6817 CheckImplicitArgumentConversions(S, Call, CC);
6818
John McCall323ed742010-05-06 08:58:33 +00006819 // Go ahead and check any implicit conversions we might have skipped.
6820 // The non-canonical typecheck is just an optimization;
6821 // CheckImplicitConversion will filter out dead implicit conversions.
6822 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006823 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006824
6825 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006826
6827 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006828 if (POE->getResultExpr())
6829 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006830 }
6831
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006832 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6833 if (OVE->getSourceExpr())
6834 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6835 return;
6836 }
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006837
John McCall323ed742010-05-06 08:58:33 +00006838 // Skip past explicit casts.
6839 if (isa<ExplicitCastExpr>(E)) {
6840 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006841 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006842 }
6843
John McCallbeb22aa2010-11-09 23:24:47 +00006844 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6845 // Do a somewhat different check with comparison operators.
6846 if (BO->isComparisonOp())
6847 return AnalyzeComparison(S, BO);
6848
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006849 // And with simple assignments.
6850 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006851 return AnalyzeAssignment(S, BO);
6852 }
John McCall323ed742010-05-06 08:58:33 +00006853
6854 // These break the otherwise-useful invariant below. Fortunately,
6855 // we don't really need to recurse into them, because any internal
6856 // expressions should have been analyzed already when they were
6857 // built into statements.
6858 if (isa<StmtExpr>(E)) return;
6859
6860 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006861 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006862
6863 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006864 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006865 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006866 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006867 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006868 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006869 if (!ChildExpr)
6870 continue;
6871
Stephen Hines651f13c2014-04-23 16:59:28 -07006872 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006873 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006874 // Ignore checking string literals that are in logical and operators.
6875 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006876 continue;
6877 AnalyzeImplicitConversions(S, ChildExpr, CC);
6878 }
Stephen Hines176edba2014-12-01 14:53:08 -08006879
6880 if (BO && BO->isLogicalOp()) {
6881 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6882 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006883 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006884
6885 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6886 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006887 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Stephen Hines176edba2014-12-01 14:53:08 -08006888 }
6889
6890 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6891 if (U->getOpcode() == UO_LNot)
6892 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCall323ed742010-05-06 08:58:33 +00006893}
6894
6895} // end anonymous namespace
6896
Stephen Hines651f13c2014-04-23 16:59:28 -07006897enum {
6898 AddressOf,
6899 FunctionPointer,
6900 ArrayPointer
6901};
6902
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006903// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6904// Returns true when emitting a warning about taking the address of a reference.
6905static bool CheckForReference(Sema &SemaRef, const Expr *E,
6906 PartialDiagnostic PD) {
6907 E = E->IgnoreParenImpCasts();
6908
6909 const FunctionDecl *FD = nullptr;
6910
6911 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6912 if (!DRE->getDecl()->getType()->isReferenceType())
6913 return false;
6914 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6915 if (!M->getMemberDecl()->getType()->isReferenceType())
6916 return false;
6917 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006918 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006919 return false;
6920 FD = Call->getDirectCallee();
6921 } else {
6922 return false;
6923 }
6924
6925 SemaRef.Diag(E->getExprLoc(), PD);
6926
6927 // If possible, point to location of function.
6928 if (FD) {
6929 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6930 }
6931
6932 return true;
6933}
6934
Stephen Hines176edba2014-12-01 14:53:08 -08006935// Returns true if the SourceLocation is expanded from any macro body.
6936// Returns false if the SourceLocation is invalid, is from not in a macro
6937// expansion, or is from expanded from a top-level macro argument.
6938static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6939 if (Loc.isInvalid())
6940 return false;
6941
6942 while (Loc.isMacroID()) {
6943 if (SM.isMacroBodyExpansion(Loc))
6944 return true;
6945 Loc = SM.getImmediateMacroCallerLoc(Loc);
6946 }
6947
6948 return false;
6949}
6950
Stephen Hines651f13c2014-04-23 16:59:28 -07006951/// \brief Diagnose pointers that are always non-null.
6952/// \param E the expression containing the pointer
6953/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6954/// compared to a null pointer
6955/// \param IsEqual True when the comparison is equal to a null pointer
6956/// \param Range Extra SourceRange to highlight in the diagnostic
6957void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6958 Expr::NullPointerConstantKind NullKind,
6959 bool IsEqual, SourceRange Range) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006960 if (!E)
6961 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07006962
6963 // Don't warn inside macros.
Stephen Hines176edba2014-12-01 14:53:08 -08006964 if (E->getExprLoc().isMacroID()) {
6965 const SourceManager &SM = getSourceManager();
6966 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6967 IsInAnyMacroBody(SM, Range.getBegin()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006968 return;
Stephen Hines176edba2014-12-01 14:53:08 -08006969 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006970 E = E->IgnoreImpCasts();
6971
6972 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6973
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006974 if (isa<CXXThisExpr>(E)) {
6975 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6976 : diag::warn_this_bool_conversion;
6977 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6978 return;
6979 }
6980
Stephen Hines651f13c2014-04-23 16:59:28 -07006981 bool IsAddressOf = false;
6982
6983 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6984 if (UO->getOpcode() != UO_AddrOf)
6985 return;
6986 IsAddressOf = true;
6987 E = UO->getSubExpr();
6988 }
6989
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006990 if (IsAddressOf) {
6991 unsigned DiagID = IsCompare
6992 ? diag::warn_address_of_reference_null_compare
6993 : diag::warn_address_of_reference_bool_conversion;
6994 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6995 << IsEqual;
6996 if (CheckForReference(*this, E, PD)) {
6997 return;
6998 }
6999 }
7000
Stephen Hines651f13c2014-04-23 16:59:28 -07007001 // Expect to find a single Decl. Skip anything more complicated.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007002 ValueDecl *D = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07007003 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7004 D = R->getDecl();
7005 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7006 D = M->getMemberDecl();
7007 }
7008
7009 // Weak Decls can be null.
7010 if (!D || D->isWeak())
7011 return;
Stephen Hines176edba2014-12-01 14:53:08 -08007012
7013 // Check for parameter decl with nonnull attribute
7014 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7015 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7016 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7017 unsigned NumArgs = FD->getNumParams();
7018 llvm::SmallBitVector AttrNonNull(NumArgs);
7019 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7020 if (!NonNull->args_size()) {
7021 AttrNonNull.set(0, NumArgs);
7022 break;
7023 }
7024 for (unsigned Val : NonNull->args()) {
7025 if (Val >= NumArgs)
7026 continue;
7027 AttrNonNull.set(Val);
7028 }
7029 }
7030 if (!AttrNonNull.empty())
7031 for (unsigned i = 0; i < NumArgs; ++i)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007032 if (FD->getParamDecl(i) == PV &&
7033 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Stephen Hines176edba2014-12-01 14:53:08 -08007034 std::string Str;
7035 llvm::raw_string_ostream S(Str);
7036 E->printPretty(S, nullptr, getPrintingPolicy());
7037 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7038 : diag::warn_cast_nonnull_to_bool;
7039 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7040 << Range << IsEqual;
7041 return;
7042 }
7043 }
7044 }
7045
Stephen Hines651f13c2014-04-23 16:59:28 -07007046 QualType T = D->getType();
7047 const bool IsArray = T->isArrayType();
7048 const bool IsFunction = T->isFunctionType();
7049
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007050 // Address of function is used to silence the function warning.
7051 if (IsAddressOf && IsFunction) {
7052 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07007053 }
7054
7055 // Found nothing.
7056 if (!IsAddressOf && !IsFunction && !IsArray)
7057 return;
7058
7059 // Pretty print the expression for the diagnostic.
7060 std::string Str;
7061 llvm::raw_string_ostream S(Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007062 E->printPretty(S, nullptr, getPrintingPolicy());
Stephen Hines651f13c2014-04-23 16:59:28 -07007063
7064 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7065 : diag::warn_impcast_pointer_to_bool;
7066 unsigned DiagType;
7067 if (IsAddressOf)
7068 DiagType = AddressOf;
7069 else if (IsFunction)
7070 DiagType = FunctionPointer;
7071 else if (IsArray)
7072 DiagType = ArrayPointer;
7073 else
7074 llvm_unreachable("Could not determine diagnostic.");
7075 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7076 << Range << IsEqual;
7077
7078 if (!IsFunction)
7079 return;
7080
7081 // Suggest '&' to silence the function warning.
7082 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7083 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7084
7085 // Check to see if '()' fixit should be emitted.
7086 QualType ReturnType;
7087 UnresolvedSet<4> NonTemplateOverloads;
7088 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7089 if (ReturnType.isNull())
7090 return;
7091
7092 if (IsCompare) {
7093 // There are two cases here. If there is null constant, the only suggest
7094 // for a pointer return type. If the null is 0, then suggest if the return
7095 // type is a pointer or an integer type.
7096 if (!ReturnType->isPointerType()) {
7097 if (NullKind == Expr::NPCK_ZeroExpression ||
7098 NullKind == Expr::NPCK_ZeroLiteral) {
7099 if (!ReturnType->isIntegerType())
7100 return;
7101 } else {
7102 return;
7103 }
7104 }
7105 } else { // !IsCompare
7106 // For function to bool, only suggest if the function pointer has bool
7107 // return type.
7108 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7109 return;
7110 }
7111 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007112 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Stephen Hines651f13c2014-04-23 16:59:28 -07007113}
7114
7115
John McCall323ed742010-05-06 08:58:33 +00007116/// Diagnoses "dangerous" implicit conversions within the given
7117/// expression (which is a full expression). Implements -Wconversion
7118/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00007119///
7120/// \param CC the "context" location of the implicit conversion, i.e.
7121/// the most location of the syntactic entity requiring the implicit
7122/// conversion
7123void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00007124 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00007125 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00007126 return;
7127
7128 // Don't diagnose for value- or type-dependent expressions.
7129 if (E->isTypeDependent() || E->isValueDependent())
7130 return;
7131
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007132 // Check for array bounds violations in cases where the check isn't triggered
7133 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7134 // ArraySubscriptExpr is on the RHS of a variable initialization.
7135 CheckArrayAccess(E);
7136
John McCallb4eb64d2010-10-08 02:01:28 +00007137 // This is not the right CC for (e.g.) a variable initialization.
7138 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00007139}
7140
Stephen Hines176edba2014-12-01 14:53:08 -08007141/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7142/// Input argument E is a logical expression.
7143void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7144 ::CheckBoolLikeConversion(*this, E, CC);
7145}
7146
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007147/// Diagnose when expression is an integer constant expression and its evaluation
7148/// results in integer overflow
7149void Sema::CheckForIntOverflow (Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08007150 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7151 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007152}
7153
Richard Smith6c3af3d2013-01-17 01:17:56 +00007154namespace {
7155/// \brief Visitor for expressions which looks for unsequenced operations on the
7156/// same object.
7157class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00007158 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7159
Richard Smith6c3af3d2013-01-17 01:17:56 +00007160 /// \brief A tree of sequenced regions within an expression. Two regions are
7161 /// unsequenced if one is an ancestor or a descendent of the other. When we
7162 /// finish processing an expression with sequencing, such as a comma
7163 /// expression, we fold its tree nodes into its parent, since they are
7164 /// unsequenced with respect to nodes we will visit later.
7165 class SequenceTree {
7166 struct Value {
7167 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7168 unsigned Parent : 31;
7169 bool Merged : 1;
7170 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00007171 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007172
7173 public:
7174 /// \brief A region within an expression which may be sequenced with respect
7175 /// to some other region.
7176 class Seq {
7177 explicit Seq(unsigned N) : Index(N) {}
7178 unsigned Index;
7179 friend class SequenceTree;
7180 public:
7181 Seq() : Index(0) {}
7182 };
7183
7184 SequenceTree() { Values.push_back(Value(0)); }
7185 Seq root() const { return Seq(0); }
7186
7187 /// \brief Create a new sequence of operations, which is an unsequenced
7188 /// subset of \p Parent. This sequence of operations is sequenced with
7189 /// respect to other children of \p Parent.
7190 Seq allocate(Seq Parent) {
7191 Values.push_back(Value(Parent.Index));
7192 return Seq(Values.size() - 1);
7193 }
7194
7195 /// \brief Merge a sequence of operations into its parent.
7196 void merge(Seq S) {
7197 Values[S.Index].Merged = true;
7198 }
7199
7200 /// \brief Determine whether two operations are unsequenced. This operation
7201 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7202 /// should have been merged into its parent as appropriate.
7203 bool isUnsequenced(Seq Cur, Seq Old) {
7204 unsigned C = representative(Cur.Index);
7205 unsigned Target = representative(Old.Index);
7206 while (C >= Target) {
7207 if (C == Target)
7208 return true;
7209 C = Values[C].Parent;
7210 }
7211 return false;
7212 }
7213
7214 private:
7215 /// \brief Pick a representative for a sequence.
7216 unsigned representative(unsigned K) {
7217 if (Values[K].Merged)
7218 // Perform path compression as we go.
7219 return Values[K].Parent = representative(Values[K].Parent);
7220 return K;
7221 }
7222 };
7223
7224 /// An object for which we can track unsequenced uses.
7225 typedef NamedDecl *Object;
7226
7227 /// Different flavors of object usage which we track. We only track the
7228 /// least-sequenced usage of each kind.
7229 enum UsageKind {
7230 /// A read of an object. Multiple unsequenced reads are OK.
7231 UK_Use,
7232 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00007233 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00007234 UK_ModAsValue,
7235 /// A modification of an object which is not sequenced before the value
7236 /// computation of the expression, such as n++.
7237 UK_ModAsSideEffect,
7238
7239 UK_Count = UK_ModAsSideEffect + 1
7240 };
7241
7242 struct Usage {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007243 Usage() : Use(nullptr), Seq() {}
Richard Smith6c3af3d2013-01-17 01:17:56 +00007244 Expr *Use;
7245 SequenceTree::Seq Seq;
7246 };
7247
7248 struct UsageInfo {
7249 UsageInfo() : Diagnosed(false) {}
7250 Usage Uses[UK_Count];
7251 /// Have we issued a diagnostic for this variable already?
7252 bool Diagnosed;
7253 };
7254 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7255
7256 Sema &SemaRef;
7257 /// Sequenced regions within the expression.
7258 SequenceTree Tree;
7259 /// Declaration modifications and references which we have seen.
7260 UsageInfoMap UsageMap;
7261 /// The region we are currently within.
7262 SequenceTree::Seq Region;
7263 /// Filled in with declarations which were modified as a side-effect
7264 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00007265 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007266 /// Expressions to check later. We defer checking these to reduce
7267 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007268 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007269
7270 /// RAII object wrapping the visitation of a sequenced subexpression of an
7271 /// expression. At the end of this process, the side-effects of the evaluation
7272 /// become sequenced with respect to the value computation of the result, so
7273 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7274 /// UK_ModAsValue.
7275 struct SequencedSubexpression {
7276 SequencedSubexpression(SequenceChecker &Self)
7277 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7278 Self.ModAsSideEffect = &ModAsSideEffect;
7279 }
7280 ~SequencedSubexpression() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007281 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7282 MI != ME; ++MI) {
7283 UsageInfo &U = Self.UsageMap[MI->first];
7284 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7285 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7286 SideEffectUsage = MI->second;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007287 }
7288 Self.ModAsSideEffect = OldModAsSideEffect;
7289 }
7290
7291 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00007292 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7293 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007294 };
7295
Richard Smith67470052013-06-20 22:21:56 +00007296 /// RAII object wrapping the visitation of a subexpression which we might
7297 /// choose to evaluate as a constant. If any subexpression is evaluated and
7298 /// found to be non-constant, this allows us to suppress the evaluation of
7299 /// the outer expression.
7300 class EvaluationTracker {
7301 public:
7302 EvaluationTracker(SequenceChecker &Self)
7303 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7304 Self.EvalTracker = this;
7305 }
7306 ~EvaluationTracker() {
7307 Self.EvalTracker = Prev;
7308 if (Prev)
7309 Prev->EvalOK &= EvalOK;
7310 }
7311
7312 bool evaluate(const Expr *E, bool &Result) {
7313 if (!EvalOK || E->isValueDependent())
7314 return false;
7315 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7316 return EvalOK;
7317 }
7318
7319 private:
7320 SequenceChecker &Self;
7321 EvaluationTracker *Prev;
7322 bool EvalOK;
7323 } *EvalTracker;
7324
Richard Smith6c3af3d2013-01-17 01:17:56 +00007325 /// \brief Find the object which is produced by the specified expression,
7326 /// if any.
7327 Object getObject(Expr *E, bool Mod) const {
7328 E = E->IgnoreParenCasts();
7329 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7330 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7331 return getObject(UO->getSubExpr(), Mod);
7332 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7333 if (BO->getOpcode() == BO_Comma)
7334 return getObject(BO->getRHS(), Mod);
7335 if (Mod && BO->isAssignmentOp())
7336 return getObject(BO->getLHS(), Mod);
7337 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7338 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7339 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7340 return ME->getMemberDecl();
7341 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7342 // FIXME: If this is a reference, map through to its value.
7343 return DRE->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007344 return nullptr;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007345 }
7346
7347 /// \brief Note that an object was modified or used by an expression.
7348 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7349 Usage &U = UI.Uses[UK];
7350 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7351 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7352 ModAsSideEffect->push_back(std::make_pair(O, U));
7353 U.Use = Ref;
7354 U.Seq = Region;
7355 }
7356 }
7357 /// \brief Check whether a modification or use conflicts with a prior usage.
7358 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7359 bool IsModMod) {
7360 if (UI.Diagnosed)
7361 return;
7362
7363 const Usage &U = UI.Uses[OtherKind];
7364 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7365 return;
7366
7367 Expr *Mod = U.Use;
7368 Expr *ModOrUse = Ref;
7369 if (OtherKind == UK_Use)
7370 std::swap(Mod, ModOrUse);
7371
7372 SemaRef.Diag(Mod->getExprLoc(),
7373 IsModMod ? diag::warn_unsequenced_mod_mod
7374 : diag::warn_unsequenced_mod_use)
7375 << O << SourceRange(ModOrUse->getExprLoc());
7376 UI.Diagnosed = true;
7377 }
7378
7379 void notePreUse(Object O, Expr *Use) {
7380 UsageInfo &U = UsageMap[O];
7381 // Uses conflict with other modifications.
7382 checkUsage(O, U, Use, UK_ModAsValue, false);
7383 }
7384 void notePostUse(Object O, Expr *Use) {
7385 UsageInfo &U = UsageMap[O];
7386 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7387 addUsage(U, O, Use, UK_Use);
7388 }
7389
7390 void notePreMod(Object O, Expr *Mod) {
7391 UsageInfo &U = UsageMap[O];
7392 // Modifications conflict with other modifications and with uses.
7393 checkUsage(O, U, Mod, UK_ModAsValue, true);
7394 checkUsage(O, U, Mod, UK_Use, false);
7395 }
7396 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7397 UsageInfo &U = UsageMap[O];
7398 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7399 addUsage(U, O, Use, UK);
7400 }
7401
7402public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00007403 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007404 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7405 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007406 Visit(E);
7407 }
7408
7409 void VisitStmt(Stmt *S) {
7410 // Skip all statements which aren't expressions for now.
7411 }
7412
7413 void VisitExpr(Expr *E) {
7414 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00007415 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007416 }
7417
7418 void VisitCastExpr(CastExpr *E) {
7419 Object O = Object();
7420 if (E->getCastKind() == CK_LValueToRValue)
7421 O = getObject(E->getSubExpr(), false);
7422
7423 if (O)
7424 notePreUse(O, E);
7425 VisitExpr(E);
7426 if (O)
7427 notePostUse(O, E);
7428 }
7429
7430 void VisitBinComma(BinaryOperator *BO) {
7431 // C++11 [expr.comma]p1:
7432 // Every value computation and side effect associated with the left
7433 // expression is sequenced before every value computation and side
7434 // effect associated with the right expression.
7435 SequenceTree::Seq LHS = Tree.allocate(Region);
7436 SequenceTree::Seq RHS = Tree.allocate(Region);
7437 SequenceTree::Seq OldRegion = Region;
7438
7439 {
7440 SequencedSubexpression SeqLHS(*this);
7441 Region = LHS;
7442 Visit(BO->getLHS());
7443 }
7444
7445 Region = RHS;
7446 Visit(BO->getRHS());
7447
7448 Region = OldRegion;
7449
7450 // Forget that LHS and RHS are sequenced. They are both unsequenced
7451 // with respect to other stuff.
7452 Tree.merge(LHS);
7453 Tree.merge(RHS);
7454 }
7455
7456 void VisitBinAssign(BinaryOperator *BO) {
7457 // The modification is sequenced after the value computation of the LHS
7458 // and RHS, so check it before inspecting the operands and update the
7459 // map afterwards.
7460 Object O = getObject(BO->getLHS(), true);
7461 if (!O)
7462 return VisitExpr(BO);
7463
7464 notePreMod(O, BO);
7465
7466 // C++11 [expr.ass]p7:
7467 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7468 // only once.
7469 //
7470 // Therefore, for a compound assignment operator, O is considered used
7471 // everywhere except within the evaluation of E1 itself.
7472 if (isa<CompoundAssignOperator>(BO))
7473 notePreUse(O, BO);
7474
7475 Visit(BO->getLHS());
7476
7477 if (isa<CompoundAssignOperator>(BO))
7478 notePostUse(O, BO);
7479
7480 Visit(BO->getRHS());
7481
Richard Smith418dd3e2013-06-26 23:16:51 +00007482 // C++11 [expr.ass]p1:
7483 // the assignment is sequenced [...] before the value computation of the
7484 // assignment expression.
7485 // C11 6.5.16/3 has no such rule.
7486 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7487 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007488 }
7489 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7490 VisitBinAssign(CAO);
7491 }
7492
7493 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7494 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7495 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7496 Object O = getObject(UO->getSubExpr(), true);
7497 if (!O)
7498 return VisitExpr(UO);
7499
7500 notePreMod(O, UO);
7501 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00007502 // C++11 [expr.pre.incr]p1:
7503 // the expression ++x is equivalent to x+=1
7504 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7505 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007506 }
7507
7508 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7509 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7510 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7511 Object O = getObject(UO->getSubExpr(), true);
7512 if (!O)
7513 return VisitExpr(UO);
7514
7515 notePreMod(O, UO);
7516 Visit(UO->getSubExpr());
7517 notePostMod(O, UO, UK_ModAsSideEffect);
7518 }
7519
7520 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7521 void VisitBinLOr(BinaryOperator *BO) {
7522 // The side-effects of the LHS of an '&&' are sequenced before the
7523 // value computation of the RHS, and hence before the value computation
7524 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7525 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00007526 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007527 {
7528 SequencedSubexpression Sequenced(*this);
7529 Visit(BO->getLHS());
7530 }
7531
7532 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007533 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007534 if (!Result)
7535 Visit(BO->getRHS());
7536 } else {
7537 // Check for unsequenced operations in the RHS, treating it as an
7538 // entirely separate evaluation.
7539 //
7540 // FIXME: If there are operations in the RHS which are unsequenced
7541 // with respect to operations outside the RHS, and those operations
7542 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00007543 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007544 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007545 }
7546 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00007547 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007548 {
7549 SequencedSubexpression Sequenced(*this);
7550 Visit(BO->getLHS());
7551 }
7552
7553 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007554 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00007555 if (Result)
7556 Visit(BO->getRHS());
7557 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007558 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00007559 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007560 }
7561
7562 // Only visit the condition, unless we can be sure which subexpression will
7563 // be chosen.
7564 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00007565 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00007566 {
7567 SequencedSubexpression Sequenced(*this);
7568 Visit(CO->getCond());
7569 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007570
7571 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00007572 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00007573 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007574 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00007575 WorkList.push_back(CO->getTrueExpr());
7576 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00007577 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007578 }
7579
Richard Smith0c0b3902013-06-30 10:40:20 +00007580 void VisitCallExpr(CallExpr *CE) {
7581 // C++11 [intro.execution]p15:
7582 // When calling a function [...], every value computation and side effect
7583 // associated with any argument expression, or with the postfix expression
7584 // designating the called function, is sequenced before execution of every
7585 // expression or statement in the body of the function [and thus before
7586 // the value computation of its result].
7587 SequencedSubexpression Sequenced(*this);
7588 Base::VisitCallExpr(CE);
7589
7590 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7591 }
7592
Richard Smith6c3af3d2013-01-17 01:17:56 +00007593 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00007594 // This is a call, so all subexpressions are sequenced before the result.
7595 SequencedSubexpression Sequenced(*this);
7596
Richard Smith6c3af3d2013-01-17 01:17:56 +00007597 if (!CCE->isListInitialization())
7598 return VisitExpr(CCE);
7599
7600 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007601 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007602 SequenceTree::Seq Parent = Region;
7603 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7604 E = CCE->arg_end();
7605 I != E; ++I) {
7606 Region = Tree.allocate(Parent);
7607 Elts.push_back(Region);
7608 Visit(*I);
7609 }
7610
7611 // Forget that the initializers are sequenced.
7612 Region = Parent;
7613 for (unsigned I = 0; I < Elts.size(); ++I)
7614 Tree.merge(Elts[I]);
7615 }
7616
7617 void VisitInitListExpr(InitListExpr *ILE) {
7618 if (!SemaRef.getLangOpts().CPlusPlus11)
7619 return VisitExpr(ILE);
7620
7621 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00007622 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00007623 SequenceTree::Seq Parent = Region;
7624 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7625 Expr *E = ILE->getInit(I);
7626 if (!E) continue;
7627 Region = Tree.allocate(Parent);
7628 Elts.push_back(Region);
7629 Visit(E);
7630 }
7631
7632 // Forget that the initializers are sequenced.
7633 Region = Parent;
7634 for (unsigned I = 0; I < Elts.size(); ++I)
7635 Tree.merge(Elts[I]);
7636 }
7637};
7638}
7639
7640void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00007641 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00007642 WorkList.push_back(E);
7643 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00007644 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00007645 SequenceChecker(*this, Item, WorkList);
7646 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00007647}
7648
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007649void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7650 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00007651 CheckImplicitConversions(E, CheckLoc);
7652 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00007653 if (!IsConstexpr && !E->isValueDependent())
7654 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00007655}
7656
John McCall15d7d122010-11-11 03:21:53 +00007657void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7658 FieldDecl *BitField,
7659 Expr *Init) {
7660 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7661}
7662
Mike Stumpf8c49212010-01-21 03:59:47 +00007663/// CheckParmsForFunctionDef - Check that the parameters of the given
7664/// function are appropriate for the definition of a function. This
7665/// takes care of any checks that cannot be performed on the
7666/// declaration itself, e.g., that the types of each of the function
7667/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00007668bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7669 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00007670 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007671 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00007672 for (; P != PEnd; ++P) {
7673 ParmVarDecl *Param = *P;
7674
Mike Stumpf8c49212010-01-21 03:59:47 +00007675 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7676 // function declarator that is part of a function definition of
7677 // that function shall not have incomplete type.
7678 //
7679 // This is also C++ [dcl.fct]p6.
7680 if (!Param->isInvalidDecl() &&
7681 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00007682 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00007683 Param->setInvalidDecl();
7684 HasInvalidParm = true;
7685 }
7686
7687 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7688 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00007689 if (CheckParameterNames &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007690 Param->getIdentifier() == nullptr &&
Mike Stumpf8c49212010-01-21 03:59:47 +00007691 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00007692 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00007693 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00007694
7695 // C99 6.7.5.3p12:
7696 // If the function declarator is not part of a definition of that
7697 // function, parameters may have incomplete type and may use the [*]
7698 // notation in their sequences of declarator specifiers to specify
7699 // variable length array types.
7700 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007701 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00007702 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00007703 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00007704 // information is added for it.
7705 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007706 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00007707 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00007708 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00007709 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007710
7711 // MSVC destroys objects passed by value in the callee. Therefore a
7712 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07007713 // object's destructor. However, we don't perform any direct access check
7714 // on the dtor.
7715 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7716 .getCXXABI()
7717 .areArgsDestroyedLeftToRightInCallee()) {
7718 if (!Param->isInvalidDecl()) {
7719 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7720 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7721 if (!ClassDecl->isInvalidDecl() &&
7722 !ClassDecl->hasIrrelevantDestructor() &&
7723 !ClassDecl->isDependentContext()) {
7724 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7725 MarkFunctionReferenced(Param->getLocation(), Destructor);
7726 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7727 }
7728 }
7729 }
Reid Kleckner9b601952013-06-21 12:45:15 +00007730 }
Mike Stumpf8c49212010-01-21 03:59:47 +00007731 }
7732
7733 return HasInvalidParm;
7734}
John McCallb7f4ffe2010-08-12 21:44:57 +00007735
7736/// CheckCastAlign - Implements -Wcast-align, which warns when a
7737/// pointer cast increases the alignment requirements.
7738void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7739 // This is actually a lot of work to potentially be doing on every
7740 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007741 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCallb7f4ffe2010-08-12 21:44:57 +00007742 return;
7743
7744 // Ignore dependent types.
7745 if (T->isDependentType() || Op->getType()->isDependentType())
7746 return;
7747
7748 // Require that the destination be a pointer type.
7749 const PointerType *DestPtr = T->getAs<PointerType>();
7750 if (!DestPtr) return;
7751
7752 // If the destination has alignment 1, we're done.
7753 QualType DestPointee = DestPtr->getPointeeType();
7754 if (DestPointee->isIncompleteType()) return;
7755 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7756 if (DestAlign.isOne()) return;
7757
7758 // Require that the source be a pointer type.
7759 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7760 if (!SrcPtr) return;
7761 QualType SrcPointee = SrcPtr->getPointeeType();
7762
7763 // Whitelist casts from cv void*. We already implicitly
7764 // whitelisted casts to cv void*, since they have alignment 1.
7765 // Also whitelist casts involving incomplete types, which implicitly
7766 // includes 'void'.
7767 if (SrcPointee->isIncompleteType()) return;
7768
7769 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7770 if (SrcAlign >= DestAlign) return;
7771
7772 Diag(TRange.getBegin(), diag::warn_cast_align)
7773 << Op->getType() << T
7774 << static_cast<unsigned>(SrcAlign.getQuantity())
7775 << static_cast<unsigned>(DestAlign.getQuantity())
7776 << TRange << Op->getSourceRange();
7777}
7778
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007779static const Type* getElementType(const Expr *BaseExpr) {
7780 const Type* EltType = BaseExpr->getType().getTypePtr();
7781 if (EltType->isAnyPointerType())
7782 return EltType->getPointeeType().getTypePtr();
7783 else if (EltType->isArrayType())
7784 return EltType->getBaseElementTypeUnsafe();
7785 return EltType;
7786}
7787
Chandler Carruthc2684342011-08-05 09:10:50 +00007788/// \brief Check whether this array fits the idiom of a size-one tail padded
7789/// array member of a struct.
7790///
7791/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7792/// commonly used to emulate flexible arrays in C89 code.
7793static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7794 const NamedDecl *ND) {
7795 if (Size != 1 || !ND) return false;
7796
7797 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7798 if (!FD) return false;
7799
7800 // Don't consider sizes resulting from macro expansions or template argument
7801 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00007802
7803 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007804 while (TInfo) {
7805 TypeLoc TL = TInfo->getTypeLoc();
7806 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00007807 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7808 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007809 TInfo = TDL->getTypeSourceInfo();
7810 continue;
7811 }
David Blaikie39e6ab42013-02-18 22:06:02 +00007812 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7813 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00007814 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7815 return false;
7816 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00007817 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00007818 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007819
7820 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00007821 if (!RD) return false;
7822 if (RD->isUnion()) return false;
7823 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7824 if (!CRD->isStandardLayout()) return false;
7825 }
Chandler Carruthc2684342011-08-05 09:10:50 +00007826
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00007827 // See if this is the last field decl in the record.
7828 const Decl *D = FD;
7829 while ((D = D->getNextDeclInContext()))
7830 if (isa<FieldDecl>(D))
7831 return false;
7832 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00007833}
7834
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007835void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007836 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00007837 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00007838 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007839 if (IndexExpr->isValueDependent())
7840 return;
7841
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00007842 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007843 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00007844 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007845 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00007846 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00007847 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00007848
Chandler Carruth34064582011-02-17 20:55:08 +00007849 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007850 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00007851 return;
Richard Smith25b009a2011-12-16 19:31:14 +00007852 if (IndexNegated)
7853 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007854
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007855 const NamedDecl *ND = nullptr;
Chandler Carruthba447122011-08-05 08:07:29 +00007856 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7857 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00007858 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00007859 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00007860
Ted Kremenek9e060ca2011-02-23 23:06:04 +00007861 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00007862 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00007863 if (!size.isStrictlyPositive())
7864 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007865
7866 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00007867 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007868 // Make sure we're comparing apples to apples when comparing index to size
7869 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7870 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00007871 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00007872 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007873 if (ptrarith_typesize != array_typesize) {
7874 // There's a cast to a different size type involved
7875 uint64_t ratio = array_typesize / ptrarith_typesize;
7876 // TODO: Be smarter about handling cases where array_typesize is not a
7877 // multiple of ptrarith_typesize
7878 if (ptrarith_typesize * ratio == array_typesize)
7879 size *= llvm::APInt(size.getBitWidth(), ratio);
7880 }
7881 }
7882
Chandler Carruth34064582011-02-17 20:55:08 +00007883 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007884 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007885 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007886 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007887
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007888 // For array subscripting the index must be less than size, but for pointer
7889 // arithmetic also allow the index (offset) to be equal to size since
7890 // computing the next address after the end of the array is legal and
7891 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00007892 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00007893 return;
7894
7895 // Also don't warn for arrays of size 1 which are members of some
7896 // structure. These are often used to approximate flexible arrays in C89
7897 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007898 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007899 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007900
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007901 // Suppress the warning if the subscript expression (as identified by the
7902 // ']' location) and the index expression are both from macro expansions
7903 // within a system header.
7904 if (ASE) {
7905 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7906 ASE->getRBracketLoc());
7907 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7908 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7909 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00007910 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007911 return;
7912 }
7913 }
7914
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007915 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007916 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007917 DiagID = diag::warn_array_index_exceeds_bounds;
7918
7919 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7920 PDiag(DiagID) << index.toString(10, true)
7921 << size.toString(10, true)
7922 << (unsigned)size.getLimitedValue(~0U)
7923 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00007924 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007925 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007926 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007927 DiagID = diag::warn_ptr_arith_precedes_bounds;
7928 if (index.isNegative()) index = -index;
7929 }
7930
7931 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7932 PDiag(DiagID) << index.toString(10, true)
7933 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007934 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00007935
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00007936 if (!ND) {
7937 // Try harder to find a NamedDecl to point at in the note.
7938 while (const ArraySubscriptExpr *ASE =
7939 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7940 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7941 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7942 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7943 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7944 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7945 }
7946
Chandler Carruth35001ca2011-02-17 21:10:52 +00007947 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007948 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7949 PDiag(diag::note_array_index_out_of_bounds)
7950 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007951}
7952
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007953void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007954 int AllowOnePastEnd = 0;
7955 while (expr) {
7956 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007957 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007958 case Stmt::ArraySubscriptExprClass: {
7959 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007960 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007961 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007962 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007963 }
7964 case Stmt::UnaryOperatorClass: {
7965 // Only unwrap the * and & unary operators
7966 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7967 expr = UO->getSubExpr();
7968 switch (UO->getOpcode()) {
7969 case UO_AddrOf:
7970 AllowOnePastEnd++;
7971 break;
7972 case UO_Deref:
7973 AllowOnePastEnd--;
7974 break;
7975 default:
7976 return;
7977 }
7978 break;
7979 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007980 case Stmt::ConditionalOperatorClass: {
7981 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7982 if (const Expr *lhs = cond->getLHS())
7983 CheckArrayAccess(lhs);
7984 if (const Expr *rhs = cond->getRHS())
7985 CheckArrayAccess(rhs);
7986 return;
7987 }
7988 default:
7989 return;
7990 }
Peter Collingbournef111d932011-04-15 00:35:48 +00007991 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007992}
John McCallf85e1932011-06-15 23:02:42 +00007993
7994//===--- CHECK: Objective-C retain cycles ----------------------------------//
7995
7996namespace {
7997 struct RetainCycleOwner {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007998 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCallf85e1932011-06-15 23:02:42 +00007999 VarDecl *Variable;
8000 SourceRange Range;
8001 SourceLocation Loc;
8002 bool Indirect;
8003
8004 void setLocsFrom(Expr *e) {
8005 Loc = e->getExprLoc();
8006 Range = e->getSourceRange();
8007 }
8008 };
8009}
8010
8011/// Consider whether capturing the given variable can possibly lead to
8012/// a retain cycle.
8013static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00008014 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00008015 // lifetime. In MRR, it's captured strongly if the variable is
8016 // __block and has an appropriate type.
8017 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8018 return false;
8019
8020 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00008021 if (ref)
8022 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00008023 return true;
8024}
8025
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008026static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00008027 while (true) {
8028 e = e->IgnoreParens();
8029 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8030 switch (cast->getCastKind()) {
8031 case CK_BitCast:
8032 case CK_LValueBitCast:
8033 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00008034 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00008035 e = cast->getSubExpr();
8036 continue;
8037
John McCallf85e1932011-06-15 23:02:42 +00008038 default:
8039 return false;
8040 }
8041 }
8042
8043 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8044 ObjCIvarDecl *ivar = ref->getDecl();
8045 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8046 return false;
8047
8048 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008049 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00008050 return false;
8051
8052 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8053 owner.Indirect = true;
8054 return true;
8055 }
8056
8057 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8058 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8059 if (!var) return false;
8060 return considerVariable(var, ref, owner);
8061 }
8062
John McCallf85e1932011-06-15 23:02:42 +00008063 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8064 if (member->isArrow()) return false;
8065
8066 // Don't count this as an indirect ownership.
8067 e = member->getBase();
8068 continue;
8069 }
8070
John McCall4b9c2d22011-11-06 09:01:30 +00008071 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8072 // Only pay attention to pseudo-objects on property references.
8073 ObjCPropertyRefExpr *pre
8074 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8075 ->IgnoreParens());
8076 if (!pre) return false;
8077 if (pre->isImplicitProperty()) return false;
8078 ObjCPropertyDecl *property = pre->getExplicitProperty();
8079 if (!property->isRetaining() &&
8080 !(property->getPropertyIvarDecl() &&
8081 property->getPropertyIvarDecl()->getType()
8082 .getObjCLifetime() == Qualifiers::OCL_Strong))
8083 return false;
8084
8085 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008086 if (pre->isSuperReceiver()) {
8087 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8088 if (!owner.Variable)
8089 return false;
8090 owner.Loc = pre->getLocation();
8091 owner.Range = pre->getSourceRange();
8092 return true;
8093 }
John McCall4b9c2d22011-11-06 09:01:30 +00008094 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8095 ->getSourceExpr());
8096 continue;
8097 }
8098
John McCallf85e1932011-06-15 23:02:42 +00008099 // Array ivars?
8100
8101 return false;
8102 }
8103}
8104
8105namespace {
8106 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8107 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8108 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008109 Context(Context), Variable(variable), Capturer(nullptr),
8110 VarWillBeReased(false) {}
8111 ASTContext &Context;
John McCallf85e1932011-06-15 23:02:42 +00008112 VarDecl *Variable;
8113 Expr *Capturer;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008114 bool VarWillBeReased;
John McCallf85e1932011-06-15 23:02:42 +00008115
8116 void VisitDeclRefExpr(DeclRefExpr *ref) {
8117 if (ref->getDecl() == Variable && !Capturer)
8118 Capturer = ref;
8119 }
8120
John McCallf85e1932011-06-15 23:02:42 +00008121 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8122 if (Capturer) return;
8123 Visit(ref->getBase());
8124 if (Capturer && ref->isFreeIvar())
8125 Capturer = ref;
8126 }
8127
8128 void VisitBlockExpr(BlockExpr *block) {
8129 // Look inside nested blocks
8130 if (block->getBlockDecl()->capturesVariable(Variable))
8131 Visit(block->getBlockDecl()->getBody());
8132 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00008133
8134 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8135 if (Capturer) return;
8136 if (OVE->getSourceExpr())
8137 Visit(OVE->getSourceExpr());
8138 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008139 void VisitBinaryOperator(BinaryOperator *BinOp) {
8140 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8141 return;
8142 Expr *LHS = BinOp->getLHS();
8143 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8144 if (DRE->getDecl() != Variable)
8145 return;
8146 if (Expr *RHS = BinOp->getRHS()) {
8147 RHS = RHS->IgnoreParenCasts();
8148 llvm::APSInt Value;
8149 VarWillBeReased =
8150 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8151 }
8152 }
8153 }
John McCallf85e1932011-06-15 23:02:42 +00008154 };
8155}
8156
8157/// Check whether the given argument is a block which captures a
8158/// variable.
8159static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8160 assert(owner.Variable && owner.Loc.isValid());
8161
8162 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00008163
8164 // Look through [^{...} copy] and Block_copy(^{...}).
8165 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8166 Selector Cmd = ME->getSelector();
8167 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8168 e = ME->getInstanceReceiver();
8169 if (!e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008170 return nullptr;
Jordan Rose1fac58a2012-09-17 17:54:30 +00008171 e = e->IgnoreParenCasts();
8172 }
8173 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8174 if (CE->getNumArgs() == 1) {
8175 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00008176 if (Fn) {
8177 const IdentifierInfo *FnI = Fn->getIdentifier();
8178 if (FnI && FnI->isStr("_Block_copy")) {
8179 e = CE->getArg(0)->IgnoreParenCasts();
8180 }
8181 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00008182 }
8183 }
8184
John McCallf85e1932011-06-15 23:02:42 +00008185 BlockExpr *block = dyn_cast<BlockExpr>(e);
8186 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008187 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00008188
8189 FindCaptureVisitor visitor(S.Context, owner.Variable);
8190 visitor.Visit(block->getBlockDecl()->getBody());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008191 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCallf85e1932011-06-15 23:02:42 +00008192}
8193
8194static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8195 RetainCycleOwner &owner) {
8196 assert(capturer);
8197 assert(owner.Variable && owner.Loc.isValid());
8198
8199 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8200 << owner.Variable << capturer->getSourceRange();
8201 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8202 << owner.Indirect << owner.Range;
8203}
8204
8205/// Check for a keyword selector that starts with the word 'add' or
8206/// 'set'.
8207static bool isSetterLikeSelector(Selector sel) {
8208 if (sel.isUnarySelector()) return false;
8209
Chris Lattner5f9e2722011-07-23 10:55:15 +00008210 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00008211 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008212 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00008213 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00008214 else if (str.startswith("add")) {
8215 // Specially whitelist 'addOperationWithBlock:'.
8216 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8217 return false;
8218 str = str.substr(3);
8219 }
John McCallf85e1932011-06-15 23:02:42 +00008220 else
8221 return false;
8222
8223 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00008224 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00008225}
8226
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008227static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8228 ObjCMessageExpr *Message) {
8229 if (S.NSMutableArrayPointer.isNull()) {
8230 IdentifierInfo *NSMutableArrayId =
8231 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8232 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8233 Message->getLocStart(),
8234 Sema::LookupOrdinaryName);
8235 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8236 if (!InterfaceDecl) {
8237 return None;
8238 }
8239 QualType NSMutableArrayObject =
8240 S.Context.getObjCInterfaceType(InterfaceDecl);
8241 S.NSMutableArrayPointer =
8242 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8243 }
8244
8245 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8246 return None;
8247 }
8248
8249 Selector Sel = Message->getSelector();
8250
8251 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8252 S.NSAPIObj->getNSArrayMethodKind(Sel);
8253 if (!MKOpt) {
8254 return None;
8255 }
8256
8257 NSAPI::NSArrayMethodKind MK = *MKOpt;
8258
8259 switch (MK) {
8260 case NSAPI::NSMutableArr_addObject:
8261 case NSAPI::NSMutableArr_insertObjectAtIndex:
8262 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8263 return 0;
8264 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8265 return 1;
8266
8267 default:
8268 return None;
8269 }
8270
8271 return None;
8272}
8273
8274static
8275Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8276 ObjCMessageExpr *Message) {
8277
8278 if (S.NSMutableDictionaryPointer.isNull()) {
8279 IdentifierInfo *NSMutableDictionaryId =
8280 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8281 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8282 Message->getLocStart(),
8283 Sema::LookupOrdinaryName);
8284 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8285 if (!InterfaceDecl) {
8286 return None;
8287 }
8288 QualType NSMutableDictionaryObject =
8289 S.Context.getObjCInterfaceType(InterfaceDecl);
8290 S.NSMutableDictionaryPointer =
8291 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8292 }
8293
8294 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8295 return None;
8296 }
8297
8298 Selector Sel = Message->getSelector();
8299
8300 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8301 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8302 if (!MKOpt) {
8303 return None;
8304 }
8305
8306 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8307
8308 switch (MK) {
8309 case NSAPI::NSMutableDict_setObjectForKey:
8310 case NSAPI::NSMutableDict_setValueForKey:
8311 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8312 return 0;
8313
8314 default:
8315 return None;
8316 }
8317
8318 return None;
8319}
8320
8321static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8322
8323 ObjCInterfaceDecl *InterfaceDecl;
8324 if (S.NSMutableSetPointer.isNull()) {
8325 IdentifierInfo *NSMutableSetId =
8326 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8327 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8328 Message->getLocStart(),
8329 Sema::LookupOrdinaryName);
8330 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8331 if (InterfaceDecl) {
8332 QualType NSMutableSetObject =
8333 S.Context.getObjCInterfaceType(InterfaceDecl);
8334 S.NSMutableSetPointer =
8335 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8336 }
8337 }
8338
8339 if (S.NSCountedSetPointer.isNull()) {
8340 IdentifierInfo *NSCountedSetId =
8341 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8342 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8343 Message->getLocStart(),
8344 Sema::LookupOrdinaryName);
8345 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8346 if (InterfaceDecl) {
8347 QualType NSCountedSetObject =
8348 S.Context.getObjCInterfaceType(InterfaceDecl);
8349 S.NSCountedSetPointer =
8350 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8351 }
8352 }
8353
8354 if (S.NSMutableOrderedSetPointer.isNull()) {
8355 IdentifierInfo *NSOrderedSetId =
8356 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8357 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8358 Message->getLocStart(),
8359 Sema::LookupOrdinaryName);
8360 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8361 if (InterfaceDecl) {
8362 QualType NSOrderedSetObject =
8363 S.Context.getObjCInterfaceType(InterfaceDecl);
8364 S.NSMutableOrderedSetPointer =
8365 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8366 }
8367 }
8368
8369 QualType ReceiverType = Message->getReceiverType();
8370
8371 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8372 ReceiverType == S.NSMutableSetPointer;
8373 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8374 ReceiverType == S.NSMutableOrderedSetPointer;
8375 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8376 ReceiverType == S.NSCountedSetPointer;
8377
8378 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8379 return None;
8380 }
8381
8382 Selector Sel = Message->getSelector();
8383
8384 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8385 if (!MKOpt) {
8386 return None;
8387 }
8388
8389 NSAPI::NSSetMethodKind MK = *MKOpt;
8390
8391 switch (MK) {
8392 case NSAPI::NSMutableSet_addObject:
8393 case NSAPI::NSOrderedSet_setObjectAtIndex:
8394 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8395 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8396 return 0;
8397 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8398 return 1;
8399 }
8400
8401 return None;
8402}
8403
8404void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8405 if (!Message->isInstanceMessage()) {
8406 return;
8407 }
8408
8409 Optional<int> ArgOpt;
8410
8411 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8412 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8413 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8414 return;
8415 }
8416
8417 int ArgIndex = *ArgOpt;
8418
8419 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8420 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8421 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8422 }
8423
8424 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8425 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8426 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8427 }
8428
8429 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8430 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8431 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8432 ValueDecl *Decl = ReceiverRE->getDecl();
8433 Diag(Message->getSourceRange().getBegin(),
8434 diag::warn_objc_circular_container)
8435 << Decl->getName();
8436 Diag(Decl->getLocation(),
8437 diag::note_objc_circular_container_declared_here)
8438 << Decl->getName();
8439 }
8440 }
8441 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8442 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8443 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8444 ObjCIvarDecl *Decl = IvarRE->getDecl();
8445 Diag(Message->getSourceRange().getBegin(),
8446 diag::warn_objc_circular_container)
8447 << Decl->getName();
8448 Diag(Decl->getLocation(),
8449 diag::note_objc_circular_container_declared_here)
8450 << Decl->getName();
8451 }
8452 }
8453 }
8454
8455}
8456
John McCallf85e1932011-06-15 23:02:42 +00008457/// Check a message send to see if it's likely to cause a retain cycle.
8458void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8459 // Only check instance methods whose selector looks like a setter.
8460 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8461 return;
8462
8463 // Try to find a variable that the receiver is strongly owned by.
8464 RetainCycleOwner owner;
8465 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008466 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00008467 return;
8468 } else {
8469 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8470 owner.Variable = getCurMethodDecl()->getSelfDecl();
8471 owner.Loc = msg->getSuperLoc();
8472 owner.Range = msg->getSuperLoc();
8473 }
8474
8475 // Check whether the receiver is captured by any of the arguments.
8476 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8477 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8478 return diagnoseRetainCycle(*this, capturer, owner);
8479}
8480
8481/// Check a property assign to see if it's likely to cause a retain cycle.
8482void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8483 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00008484 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00008485 return;
8486
8487 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8488 diagnoseRetainCycle(*this, capturer, owner);
8489}
8490
Jordan Rosee10f4d32012-09-15 02:48:31 +00008491void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8492 RetainCycleOwner Owner;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008493 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosee10f4d32012-09-15 02:48:31 +00008494 return;
8495
8496 // Because we don't have an expression for the variable, we have to set the
8497 // location explicitly here.
8498 Owner.Loc = Var->getLocation();
8499 Owner.Range = Var->getSourceRange();
8500
8501 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8502 diagnoseRetainCycle(*this, Capturer, Owner);
8503}
8504
Ted Kremenek9d084012012-12-21 08:04:28 +00008505static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8506 Expr *RHS, bool isProperty) {
8507 // Check if RHS is an Objective-C object literal, which also can get
8508 // immediately zapped in a weak reference. Note that we explicitly
8509 // allow ObjCStringLiterals, since those are designed to never really die.
8510 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008511
Ted Kremenekd3292c82012-12-21 22:46:35 +00008512 // This enum needs to match with the 'select' in
8513 // warn_objc_arc_literal_assign (off-by-1).
8514 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8515 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8516 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00008517
8518 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00008519 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00008520 << (isProperty ? 0 : 1)
8521 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00008522
8523 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00008524}
8525
Ted Kremenekb29b30f2012-12-21 19:45:30 +00008526static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8527 Qualifiers::ObjCLifetime LT,
8528 Expr *RHS, bool isProperty) {
8529 // Strip off any implicit cast added to get to the one ARC-specific.
8530 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8531 if (cast->getCastKind() == CK_ARCConsumeObject) {
8532 S.Diag(Loc, diag::warn_arc_retained_assign)
8533 << (LT == Qualifiers::OCL_ExplicitNone)
8534 << (isProperty ? 0 : 1)
8535 << RHS->getSourceRange();
8536 return true;
8537 }
8538 RHS = cast->getSubExpr();
8539 }
8540
8541 if (LT == Qualifiers::OCL_Weak &&
8542 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8543 return true;
8544
8545 return false;
8546}
8547
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008548bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8549 QualType LHS, Expr *RHS) {
8550 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8551
8552 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8553 return false;
8554
8555 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8556 return true;
8557
8558 return false;
8559}
8560
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008561void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8562 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008563 QualType LHSType;
8564 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07008565 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008566 ObjCPropertyRefExpr *PRE
8567 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8568 if (PRE && !PRE->isImplicitProperty()) {
8569 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8570 if (PD)
8571 LHSType = PD->getType();
8572 }
8573
8574 if (LHSType.isNull())
8575 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00008576
8577 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8578
8579 if (LT == Qualifiers::OCL_Weak) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008580 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose7a270482012-09-28 22:21:35 +00008581 getCurFunction()->markSafeWeakUse(LHS);
8582 }
8583
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008584 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8585 return;
Jordan Rose7a270482012-09-28 22:21:35 +00008586
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008587 // FIXME. Check for other life times.
8588 if (LT != Qualifiers::OCL_None)
8589 return;
8590
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008591 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008592 if (PRE->isImplicitProperty())
8593 return;
8594 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8595 if (!PD)
8596 return;
8597
Bill Wendlingad017fa2012-12-20 19:22:21 +00008598 unsigned Attributes = PD->getPropertyAttributes();
8599 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008600 // when 'assign' attribute was not explicitly specified
8601 // by user, ignore it and rely on property type itself
8602 // for lifetime info.
8603 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8604 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8605 LHSType->isObjCRetainableType())
8606 return;
8607
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008608 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00008609 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008610 Diag(Loc, diag::warn_arc_retained_property_assign)
8611 << RHS->getSourceRange();
8612 return;
8613 }
8614 RHS = cast->getSubExpr();
8615 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00008616 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00008617 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00008618 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8619 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00008620 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00008621 }
8622}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008623
8624//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8625
8626namespace {
8627bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8628 SourceLocation StmtLoc,
8629 const NullStmt *Body) {
8630 // Do not warn if the body is a macro that expands to nothing, e.g:
8631 //
8632 // #define CALL(x)
8633 // if (condition)
8634 // CALL(0);
8635 //
8636 if (Body->hasLeadingEmptyMacro())
8637 return false;
8638
8639 // Get line numbers of statement and body.
8640 bool StmtLineInvalid;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008641 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008642 &StmtLineInvalid);
8643 if (StmtLineInvalid)
8644 return false;
8645
8646 bool BodyLineInvalid;
8647 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8648 &BodyLineInvalid);
8649 if (BodyLineInvalid)
8650 return false;
8651
8652 // Warn if null statement and body are on the same line.
8653 if (StmtLine != BodyLine)
8654 return false;
8655
8656 return true;
8657}
8658} // Unnamed namespace
8659
8660void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8661 const Stmt *Body,
8662 unsigned DiagID) {
8663 // Since this is a syntactic check, don't emit diagnostic for template
8664 // instantiations, this just adds noise.
8665 if (CurrentInstantiationScope)
8666 return;
8667
8668 // The body should be a null statement.
8669 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8670 if (!NBody)
8671 return;
8672
8673 // Do the usual checks.
8674 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8675 return;
8676
8677 Diag(NBody->getSemiLoc(), DiagID);
8678 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8679}
8680
8681void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8682 const Stmt *PossibleBody) {
8683 assert(!CurrentInstantiationScope); // Ensured by caller
8684
8685 SourceLocation StmtLoc;
8686 const Stmt *Body;
8687 unsigned DiagID;
8688 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8689 StmtLoc = FS->getRParenLoc();
8690 Body = FS->getBody();
8691 DiagID = diag::warn_empty_for_body;
8692 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8693 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8694 Body = WS->getBody();
8695 DiagID = diag::warn_empty_while_body;
8696 } else
8697 return; // Neither `for' nor `while'.
8698
8699 // The body should be a null statement.
8700 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8701 if (!NBody)
8702 return;
8703
8704 // Skip expensive checks if diagnostic is disabled.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008705 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008706 return;
8707
8708 // Do the usual checks.
8709 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8710 return;
8711
8712 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8713 // noise level low, emit diagnostics only if for/while is followed by a
8714 // CompoundStmt, e.g.:
8715 // for (int i = 0; i < n; i++);
8716 // {
8717 // a(i);
8718 // }
8719 // or if for/while is followed by a statement with more indentation
8720 // than for/while itself:
8721 // for (int i = 0; i < n; i++);
8722 // a(i);
8723 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8724 if (!ProbableTypo) {
8725 bool BodyColInvalid;
8726 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8727 PossibleBody->getLocStart(),
8728 &BodyColInvalid);
8729 if (BodyColInvalid)
8730 return;
8731
8732 bool StmtColInvalid;
8733 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8734 S->getLocStart(),
8735 &StmtColInvalid);
8736 if (StmtColInvalid)
8737 return;
8738
8739 if (BodyCol > StmtCol)
8740 ProbableTypo = true;
8741 }
8742
8743 if (ProbableTypo) {
8744 Diag(NBody->getSemiLoc(), DiagID);
8745 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8746 }
8747}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008748
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008749//===--- CHECK: Warn on self move with std::move. -------------------------===//
8750
8751/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8752void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8753 SourceLocation OpLoc) {
8754
8755 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8756 return;
8757
8758 if (!ActiveTemplateInstantiations.empty())
8759 return;
8760
8761 // Strip parens and casts away.
8762 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8763 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8764
8765 // Check for a call expression
8766 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8767 if (!CE || CE->getNumArgs() != 1)
8768 return;
8769
8770 // Check for a call to std::move
8771 const FunctionDecl *FD = CE->getDirectCallee();
8772 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8773 !FD->getIdentifier()->isStr("move"))
8774 return;
8775
8776 // Get argument from std::move
8777 RHSExpr = CE->getArg(0);
8778
8779 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8780 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8781
8782 // Two DeclRefExpr's, check that the decls are the same.
8783 if (LHSDeclRef && RHSDeclRef) {
8784 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8785 return;
8786 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8787 RHSDeclRef->getDecl()->getCanonicalDecl())
8788 return;
8789
8790 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8791 << LHSExpr->getSourceRange()
8792 << RHSExpr->getSourceRange();
8793 return;
8794 }
8795
8796 // Member variables require a different approach to check for self moves.
8797 // MemberExpr's are the same if every nested MemberExpr refers to the same
8798 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8799 // the base Expr's are CXXThisExpr's.
8800 const Expr *LHSBase = LHSExpr;
8801 const Expr *RHSBase = RHSExpr;
8802 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8803 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8804 if (!LHSME || !RHSME)
8805 return;
8806
8807 while (LHSME && RHSME) {
8808 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8809 RHSME->getMemberDecl()->getCanonicalDecl())
8810 return;
8811
8812 LHSBase = LHSME->getBase();
8813 RHSBase = RHSME->getBase();
8814 LHSME = dyn_cast<MemberExpr>(LHSBase);
8815 RHSME = dyn_cast<MemberExpr>(RHSBase);
8816 }
8817
8818 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8819 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8820 if (LHSDeclRef && RHSDeclRef) {
8821 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8822 return;
8823 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8824 RHSDeclRef->getDecl()->getCanonicalDecl())
8825 return;
8826
8827 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8828 << LHSExpr->getSourceRange()
8829 << RHSExpr->getSourceRange();
8830 return;
8831 }
8832
8833 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8834 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8835 << LHSExpr->getSourceRange()
8836 << RHSExpr->getSourceRange();
8837}
8838
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008839//===--- Layout compatibility ----------------------------------------------//
8840
8841namespace {
8842
8843bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8844
8845/// \brief Check if two enumeration types are layout-compatible.
8846bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8847 // C++11 [dcl.enum] p8:
8848 // Two enumeration types are layout-compatible if they have the same
8849 // underlying type.
8850 return ED1->isComplete() && ED2->isComplete() &&
8851 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8852}
8853
8854/// \brief Check if two fields are layout-compatible.
8855bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8856 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8857 return false;
8858
8859 if (Field1->isBitField() != Field2->isBitField())
8860 return false;
8861
8862 if (Field1->isBitField()) {
8863 // Make sure that the bit-fields are the same length.
8864 unsigned Bits1 = Field1->getBitWidthValue(C);
8865 unsigned Bits2 = Field2->getBitWidthValue(C);
8866
8867 if (Bits1 != Bits2)
8868 return false;
8869 }
8870
8871 return true;
8872}
8873
8874/// \brief Check if two standard-layout structs are layout-compatible.
8875/// (C++11 [class.mem] p17)
8876bool isLayoutCompatibleStruct(ASTContext &C,
8877 RecordDecl *RD1,
8878 RecordDecl *RD2) {
8879 // If both records are C++ classes, check that base classes match.
8880 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8881 // If one of records is a CXXRecordDecl we are in C++ mode,
8882 // thus the other one is a CXXRecordDecl, too.
8883 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8884 // Check number of base classes.
8885 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8886 return false;
8887
8888 // Check the base classes.
8889 for (CXXRecordDecl::base_class_const_iterator
8890 Base1 = D1CXX->bases_begin(),
8891 BaseEnd1 = D1CXX->bases_end(),
8892 Base2 = D2CXX->bases_begin();
8893 Base1 != BaseEnd1;
8894 ++Base1, ++Base2) {
8895 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8896 return false;
8897 }
8898 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8899 // If only RD2 is a C++ class, it should have zero base classes.
8900 if (D2CXX->getNumBases() > 0)
8901 return false;
8902 }
8903
8904 // Check the fields.
8905 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8906 Field2End = RD2->field_end(),
8907 Field1 = RD1->field_begin(),
8908 Field1End = RD1->field_end();
8909 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8910 if (!isLayoutCompatible(C, *Field1, *Field2))
8911 return false;
8912 }
8913 if (Field1 != Field1End || Field2 != Field2End)
8914 return false;
8915
8916 return true;
8917}
8918
8919/// \brief Check if two standard-layout unions are layout-compatible.
8920/// (C++11 [class.mem] p18)
8921bool isLayoutCompatibleUnion(ASTContext &C,
8922 RecordDecl *RD1,
8923 RecordDecl *RD2) {
8924 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07008925 for (auto *Field2 : RD2->fields())
8926 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008927
Stephen Hines651f13c2014-04-23 16:59:28 -07008928 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008929 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8930 I = UnmatchedFields.begin(),
8931 E = UnmatchedFields.end();
8932
8933 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008934 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008935 bool Result = UnmatchedFields.erase(*I);
8936 (void) Result;
8937 assert(Result);
8938 break;
8939 }
8940 }
8941 if (I == E)
8942 return false;
8943 }
8944
8945 return UnmatchedFields.empty();
8946}
8947
8948bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8949 if (RD1->isUnion() != RD2->isUnion())
8950 return false;
8951
8952 if (RD1->isUnion())
8953 return isLayoutCompatibleUnion(C, RD1, RD2);
8954 else
8955 return isLayoutCompatibleStruct(C, RD1, RD2);
8956}
8957
8958/// \brief Check if two types are layout-compatible in C++11 sense.
8959bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8960 if (T1.isNull() || T2.isNull())
8961 return false;
8962
8963 // C++11 [basic.types] p11:
8964 // If two types T1 and T2 are the same type, then T1 and T2 are
8965 // layout-compatible types.
8966 if (C.hasSameType(T1, T2))
8967 return true;
8968
8969 T1 = T1.getCanonicalType().getUnqualifiedType();
8970 T2 = T2.getCanonicalType().getUnqualifiedType();
8971
8972 const Type::TypeClass TC1 = T1->getTypeClass();
8973 const Type::TypeClass TC2 = T2->getTypeClass();
8974
8975 if (TC1 != TC2)
8976 return false;
8977
8978 if (TC1 == Type::Enum) {
8979 return isLayoutCompatible(C,
8980 cast<EnumType>(T1)->getDecl(),
8981 cast<EnumType>(T2)->getDecl());
8982 } else if (TC1 == Type::Record) {
8983 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8984 return false;
8985
8986 return isLayoutCompatible(C,
8987 cast<RecordType>(T1)->getDecl(),
8988 cast<RecordType>(T2)->getDecl());
8989 }
8990
8991 return false;
8992}
8993}
8994
8995//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8996
8997namespace {
8998/// \brief Given a type tag expression find the type tag itself.
8999///
9000/// \param TypeExpr Type tag expression, as it appears in user's code.
9001///
9002/// \param VD Declaration of an identifier that appears in a type tag.
9003///
9004/// \param MagicValue Type tag magic value.
9005bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9006 const ValueDecl **VD, uint64_t *MagicValue) {
9007 while(true) {
9008 if (!TypeExpr)
9009 return false;
9010
9011 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9012
9013 switch (TypeExpr->getStmtClass()) {
9014 case Stmt::UnaryOperatorClass: {
9015 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9016 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9017 TypeExpr = UO->getSubExpr();
9018 continue;
9019 }
9020 return false;
9021 }
9022
9023 case Stmt::DeclRefExprClass: {
9024 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9025 *VD = DRE->getDecl();
9026 return true;
9027 }
9028
9029 case Stmt::IntegerLiteralClass: {
9030 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9031 llvm::APInt MagicValueAPInt = IL->getValue();
9032 if (MagicValueAPInt.getActiveBits() <= 64) {
9033 *MagicValue = MagicValueAPInt.getZExtValue();
9034 return true;
9035 } else
9036 return false;
9037 }
9038
9039 case Stmt::BinaryConditionalOperatorClass:
9040 case Stmt::ConditionalOperatorClass: {
9041 const AbstractConditionalOperator *ACO =
9042 cast<AbstractConditionalOperator>(TypeExpr);
9043 bool Result;
9044 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9045 if (Result)
9046 TypeExpr = ACO->getTrueExpr();
9047 else
9048 TypeExpr = ACO->getFalseExpr();
9049 continue;
9050 }
9051 return false;
9052 }
9053
9054 case Stmt::BinaryOperatorClass: {
9055 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9056 if (BO->getOpcode() == BO_Comma) {
9057 TypeExpr = BO->getRHS();
9058 continue;
9059 }
9060 return false;
9061 }
9062
9063 default:
9064 return false;
9065 }
9066 }
9067}
9068
9069/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9070///
9071/// \param TypeExpr Expression that specifies a type tag.
9072///
9073/// \param MagicValues Registered magic values.
9074///
9075/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9076/// kind.
9077///
9078/// \param TypeInfo Information about the corresponding C type.
9079///
9080/// \returns true if the corresponding C type was found.
9081bool GetMatchingCType(
9082 const IdentifierInfo *ArgumentKind,
9083 const Expr *TypeExpr, const ASTContext &Ctx,
9084 const llvm::DenseMap<Sema::TypeTagMagicValue,
9085 Sema::TypeTagData> *MagicValues,
9086 bool &FoundWrongKind,
9087 Sema::TypeTagData &TypeInfo) {
9088 FoundWrongKind = false;
9089
9090 // Variable declaration that has type_tag_for_datatype attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009091 const ValueDecl *VD = nullptr;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009092
9093 uint64_t MagicValue;
9094
9095 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9096 return false;
9097
9098 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009099 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009100 if (I->getArgumentKind() != ArgumentKind) {
9101 FoundWrongKind = true;
9102 return false;
9103 }
9104 TypeInfo.Type = I->getMatchingCType();
9105 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9106 TypeInfo.MustBeNull = I->getMustBeNull();
9107 return true;
9108 }
9109 return false;
9110 }
9111
9112 if (!MagicValues)
9113 return false;
9114
9115 llvm::DenseMap<Sema::TypeTagMagicValue,
9116 Sema::TypeTagData>::const_iterator I =
9117 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9118 if (I == MagicValues->end())
9119 return false;
9120
9121 TypeInfo = I->second;
9122 return true;
9123}
9124} // unnamed namespace
9125
9126void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9127 uint64_t MagicValue, QualType Type,
9128 bool LayoutCompatible,
9129 bool MustBeNull) {
9130 if (!TypeTagForDatatypeMagicValues)
9131 TypeTagForDatatypeMagicValues.reset(
9132 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9133
9134 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9135 (*TypeTagForDatatypeMagicValues)[Magic] =
9136 TypeTagData(Type, LayoutCompatible, MustBeNull);
9137}
9138
9139namespace {
9140bool IsSameCharType(QualType T1, QualType T2) {
9141 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9142 if (!BT1)
9143 return false;
9144
9145 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9146 if (!BT2)
9147 return false;
9148
9149 BuiltinType::Kind T1Kind = BT1->getKind();
9150 BuiltinType::Kind T2Kind = BT2->getKind();
9151
9152 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9153 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9154 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9155 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9156}
9157} // unnamed namespace
9158
9159void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9160 const Expr * const *ExprArgs) {
9161 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9162 bool IsPointerAttr = Attr->getIsPointer();
9163
9164 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9165 bool FoundWrongKind;
9166 TypeTagData TypeInfo;
9167 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9168 TypeTagForDatatypeMagicValues.get(),
9169 FoundWrongKind, TypeInfo)) {
9170 if (FoundWrongKind)
9171 Diag(TypeTagExpr->getExprLoc(),
9172 diag::warn_type_tag_for_datatype_wrong_kind)
9173 << TypeTagExpr->getSourceRange();
9174 return;
9175 }
9176
9177 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9178 if (IsPointerAttr) {
9179 // Skip implicit cast of pointer to `void *' (as a function argument).
9180 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00009181 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00009182 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009183 ArgumentExpr = ICE->getSubExpr();
9184 }
9185 QualType ArgumentType = ArgumentExpr->getType();
9186
9187 // Passing a `void*' pointer shouldn't trigger a warning.
9188 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9189 return;
9190
9191 if (TypeInfo.MustBeNull) {
9192 // Type tag with matching void type requires a null pointer.
9193 if (!ArgumentExpr->isNullPointerConstant(Context,
9194 Expr::NPC_ValueDependentIsNotNull)) {
9195 Diag(ArgumentExpr->getExprLoc(),
9196 diag::warn_type_safety_null_pointer_required)
9197 << ArgumentKind->getName()
9198 << ArgumentExpr->getSourceRange()
9199 << TypeTagExpr->getSourceRange();
9200 }
9201 return;
9202 }
9203
9204 QualType RequiredType = TypeInfo.Type;
9205 if (IsPointerAttr)
9206 RequiredType = Context.getPointerType(RequiredType);
9207
9208 bool mismatch = false;
9209 if (!TypeInfo.LayoutCompatible) {
9210 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9211
9212 // C++11 [basic.fundamental] p1:
9213 // Plain char, signed char, and unsigned char are three distinct types.
9214 //
9215 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9216 // char' depending on the current char signedness mode.
9217 if (mismatch)
9218 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9219 RequiredType->getPointeeType())) ||
9220 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9221 mismatch = false;
9222 } else
9223 if (IsPointerAttr)
9224 mismatch = !isLayoutCompatible(Context,
9225 ArgumentType->getPointeeType(),
9226 RequiredType->getPointeeType());
9227 else
9228 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9229
9230 if (mismatch)
9231 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07009232 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00009233 << TypeInfo.LayoutCompatible << RequiredType
9234 << ArgumentExpr->getSourceRange()
9235 << TypeTagExpr->getSourceRange();
9236}
Stephen Hines651f13c2014-04-23 16:59:28 -07009237